-
Notifications
You must be signed in to change notification settings - Fork 0
/
port.c
70 lines (56 loc) · 1.53 KB
/
port.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//******************************************************************************
#include "port.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <assert.h>
int fd_listen = -1;
int fd_connect = -1;
//******************************************************************************
void port_create(int port)
{
assert(fd_connect < 0);
fd_listen = socket(AF_INET, SOCK_STREAM, 0);
assert(fd_listen >= 0);
struct sockaddr_in addr_server;
memset(&addr_server, 0, sizeof(struct sockaddr_in));
addr_server.sin_family = AF_INET;
addr_server.sin_addr.s_addr = htonl(INADDR_ANY);
addr_server.sin_port = htons(port);
int ret = bind(fd_listen, (struct sockaddr*)&addr_server, sizeof(addr_server));
assert(ret >= 0);
ret = listen(fd_listen, 1);
assert(ret >= 0);
fd_connect = accept(fd_listen, NULL, NULL);
assert(fd_connect >= 0);
}
void port_close()
{
assert(fd_connect >= 0);
close(fd_connect);
fd_connect = -1;
close(fd_listen);
fd_listen = -1;
}
//******************************************************************************
void port_write(const char *str, int len)
{
assert(fd_connect >= 0);
int n = write(fd_connect, str, len);
assert(n == len);
}
int port_read_char()
{
assert(fd_connect >= 0);
char c = '\0';
int n = read(fd_connect, &c, 1);
if (n == 0)
return EOF;
return c;
}
//******************************************************************************