-
Notifications
You must be signed in to change notification settings - Fork 4
/
socket.c
114 lines (93 loc) · 1.83 KB
/
socket.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "ftpscan.h"
static int do_accept(int);
int
connect_server(in_addr_t address, in_port_t port)
{
struct sockaddr_in sin;
int fd;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
sin.sin_addr.s_addr = address;
if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
fprintf(stderr, "socket failed\n");
exit(EXIT_FAILURE);
}
if(connect(fd, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
error("connect failed");
exit(EXIT_FAILURE);
}
return fd;
}
int
listen_port(in_port_t port)
{
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(port);
int s;
if((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
fprintf(stderr, "socket() failed\n");
return -1;
}
if(bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
error("bind() failed for port %d", port);
return -1;
}
if(listen(s, 5) < 0) {
fprintf(stderr, "listen() failed\n");
return -1;
}
return s;
}
int
set_nonblocking(int fd)
{
int flags;
flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
return 0;
}
int
set_blocking(fd)
{
int flags;
flags = fcntl(fd, F_GETFL, 0);
flags &= ~O_NONBLOCK;
fcntl(fd, F_SETFL, flags);
return 0;
}
int
wait_accept(int s, int timeout)
{
set_nonblocking(s);
struct pollfd pfd;
pfd.fd = s;
pfd.events = POLLIN;
pfd.revents = 0;
if(poll(&pfd, 1, timeout) == 0)
return 0;
if((pfd.revents & POLLIN) == 0)
return -1;
return do_accept(s);
}
static int
do_accept(int s)
{
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
int new_socket;
if((new_socket = accept(s, (struct sockaddr *)&sin, &len)) < 0) {
error("accept() failed");
return -1;
}
return new_socket;
}