-
Notifications
You must be signed in to change notification settings - Fork 0
/
dial.c
59 lines (53 loc) · 1.37 KB
/
dial.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
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct sockaddr sockaddr;
typedef struct sockaddr_in sockaddr_in;
int dial(FILE **in, FILE **out, char *ip, char *port)
{
int con, n;
sockaddr_in addr;
if ((con = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
return -1;
memset(&addr, 0, sizeof (addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = ip? inet_addr(ip) : htonl(INADDR_LOOPBACK);
addr.sin_port = htons(atoi(port));
if (connect(con, (sockaddr*) &addr, sizeof (addr)) < 0)
return -2;
*in = fdopen(dup(con), "r");
*out = fdopen(con, "w");
return 0;
}
int host(FILE **in, FILE **out, char *port)
{
static int fd = -1;
int con;
socklen_t clen;
sockaddr_in server, client;
if (fd < 0) {
if ((fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
return -1;
memset(&server, 0, sizeof (server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(atoi(port));
if (bind(fd, (sockaddr*) &server, sizeof (server)) < 0)
return -2;
listen(fd, 5);
clen = sizeof(client);
}
if ((con = accept(fd, (sockaddr*) &client, &clen)) < 0)
return -3;
*in = fdopen(dup(con), "r");
*out = fdopen(con, "w");
return 0;
}