forked from jlyo/tcping
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.c
97 lines (84 loc) · 2.05 KB
/
tcp.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
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include "tcp.h"
int lookup(char *host, char *portnr, struct addrinfo **res)
{
struct addrinfo hints;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_NUMERICSERV;
hints.ai_protocol = 0;
return getaddrinfo(host, portnr, &hints, res);
}
int connect_to(struct addrinfo *addr, struct timeval *rtt, int timeout)
{
int fd;
struct timeval start;
int connect_result;
const int on = 1;
struct timeval tm;
fd_set set;
int flags;
int ret;
/* int flags; */
int rv = 0;
/* try to connect for each of the entries: */
while (addr != NULL) {
/* create socket */
if ((fd =
socket(addr->ai_family, addr->ai_socktype,
addr->ai_protocol)) == -1)
goto next_addr0;
if (setsockopt
(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
goto next_addr1;
if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
goto next_addr1;
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1)
goto next_addr1;
if (gettimeofday(&start, NULL) == -1)
goto next_addr1;
/* connect to peer */
connect_result = connect(fd, addr->ai_addr, addr->ai_addrlen);
if (connect_result == -1 && errno != EINPROGRESS) {
goto next_addr1;
}
tm.tv_sec = timeout;
tm.tv_usec = 0;
FD_ZERO(&set);
FD_SET(fd, &set);
ret = select(fd+1, NULL, &set, NULL, &tm);
switch(ret){
case 0:/* timeout */
case -1:
goto next_addr1;
break;
default:/* Connection ok or refused*/
ret = write(fd, "", 0);/* only test, no data send */
if(ret <0) goto next_addr1;
break;
}
if (gettimeofday(rtt, NULL) == -1)
goto next_addr1;
rtt->tv_sec = rtt->tv_sec - start.tv_sec;
rtt->tv_usec = rtt->tv_usec - start.tv_usec;
close(fd);
return 0;
next_addr1:
close(fd);
next_addr0:
addr = addr->ai_next;
}
rv = rv ? rv : -errno;
return rv;
}