-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathtcp.c
81 lines (72 loc) · 2.02 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
/* pingcheck - Check connectivity of interfaces in OpenWRT
*
* Copyright (C) 2016 Bruno Randolf <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "main.h"
/* keep libc includes before linux headers for musl compatibility */
#include <netinet/in.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/if.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
int tcp_connect(const char* ifname, int dst, int port)
{
int fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (fd == -1) {
warn("Could not open TCP socket");
return -1;
}
/* bind to interface */
if (ifname != NULL) {
if (strlen(ifname) >= IFNAMSIZ) {
fprintf(stderr, "TCP: ifname too long");
return -1;
}
struct ifreq ifr;
strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
int ret
= setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
if (ret < 0) {
warn("TCP: could not bind to '%s'", ifname);
close(fd);
return -1;
}
}
/* make non-blocking */
unsigned int fl = fcntl(fd, F_GETFL, 0);
fl |= O_NONBLOCK;
fcntl(fd, F_SETFL, fl);
/* connect */
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = dst;
int ret = connect(fd, (struct sockaddr*)&addr, sizeof(struct sockaddr_in));
if (ret == -1 && errno != EINPROGRESS) {
warn("TCP: could not connect");
return -1;
}
return fd;
}
bool tcp_check_connect(int fd)
{
int err;
socklen_t len = sizeof(err);
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len);
return err == 0;
}