UDP打洞

在传统的客户机服务器的架构中, 客户机比较隐秘(往往只有内网IP), 服务机有周知的网络层地址(公网IP)和端口号。一般情况下客户机向服务机主动发起通信。两个没有公网IP并且不再同一个内网的客户机如何通信呢?其实不难想到,解决方案大概有这么几种:

  1. 一个有公网IP的服务机, 两个客户机分别和服务机通信, 服务机转发两者的通信。服务机扮演的保密送信员的角色, 两个客户机不知道彼此的IP地址, 通信的质量依赖于服务机和客户机之间的链路

  2. 两个客户机直接通信。需要满足一些前提条件, 在此之前, 有一个问题, 在传统的C/S架构中, 服务机为什么能够给客户机发送信息, 它是怎么找到客户机的, 客户机没有公网IP。在客户机与服务机通信中需要经过下面几个步骤。

i. 客户机将需要发送的消息放入tcp/udp的数据部分, 在tcp/udp首部加入源端口和目标端口, 便于运输层多路复用和多路分解。tcp/udp能够找到接收消息的进程。
ii. 网络层(ipv4)首部添加目标主机的IP地址和源主机的IP地址
iii. 数据链路层, 添加源MAC地址和目标MAC地址, 如果目标主机和源主机位于同一个子网, 这里的目标MAC地址应该是通过arp地址解析协议得到的目标主机的MAC地址, 如果不在同一个子网, 就需要路由器转发这个分组, 此时接收这个分组的主机是路由器, 因此目标主机的MAC地址应该是路由器的MAC地址,不是广播地址。

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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

#define MAX_CONNECTION_QUEUE_SIZE 20
typedef unsigned char byte;

// UDP hole punching example, for TCP set SO_REUSEADDR
// @date 2021.12.13
// @author ourfor
// @email ourfor@qq.com

/**
* @brief UDP hold punching client
*
* @param ip server ip
* @param port server port
*/
void client(char * ip, int port) {
int sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd == -1) {
printf("socket create failed, %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
struct sockaddr_in address;
socklen_t address_len = sizeof(struct sockaddr_in);
memset(&address, 0x00, sizeof(struct sockaddr_in));
address.sin_family = PF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = inet_addr(ip);

// if (connect(sockfd, (struct sockaddr *)&address,
// sizeof(struct sockaddr_in)) == -1) {
// printf("connect server(%s:%d) failed, %s\n", ip, port,
// strerror(errno)); exit(EXIT_FAILURE);
// }
byte buff[128] = {'H', 'E', 'L', 'L', 'O', '\0'};
sendto(sockfd, (void *)buff, 5, 0, (sockaddr *)&address, address_len);

struct sockaddr_in peer_address;
recvfrom(sockfd, (void *)&peer_address, sizeof(struct sockaddr_in), 0,
(sockaddr *)&address, &address_len);
printf("peer address(NAT %s:%d)\n", inet_ntoa(peer_address.sin_addr),
ntohs(peer_address.sin_port));

sprintf((char *)buff, "My process id is %d", getpid());
sendto(sockfd, buff, strlen((char *)buff), 0, (sockaddr *)&peer_address,
address_len);

recvfrom(sockfd, (void *)buff, 22, 0, (sockaddr *)&peer_address,
&address_len);
printf("receive from peer(%s:%d): %s\n", inet_ntoa(peer_address.sin_addr),
ntohs(peer_address.sin_port), buff);
}

void server(int port) {
int sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd == -1) {
printf("socket create failed, %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
struct sockaddr_in address;
memset(&address, 0x00, sizeof(struct sockaddr_in));
address.sin_family = PF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = INADDR_ANY;

if (bind(sockfd, (sockaddr *)&address, sizeof(struct sockaddr_in)) == -1) {
printf("bind socket(*:%d) failed, %s\n", port, strerror(errno));
exit(EXIT_FAILURE);
}

// if (listen(sockfd, MAX_CONNECTION_QUEUE_SIZE) == -1) {
// printf("listen failed, %s\n", strerror(errno));
// exit(EXIT_FAILURE);
// }

byte buff[10] = {0x00};
while (1) {
struct sockaddr_in clients[2];
struct sockaddr_in address;
socklen_t address_len = sizeof(struct sockaddr_in);
// int connection = accept(sockfd, (sockaddr *)&address, &address_len);
// if (connection == -1) {
// printf("connection failed, %s\n", strerror(errno));
// continue;
// }

// client A
recvfrom(sockfd, buff, 10, 0, (sockaddr *)&address, &address_len);
memcpy((void *)clients, &address, sizeof(struct sockaddr_in));
printf("client(%s:%d) connected\n", inet_ntoa(clients[0].sin_addr),
ntohs(clients[0].sin_port));

// client B
recvfrom(sockfd, buff, 10, 0, (sockaddr *)&address, &address_len);
memcpy((void *)(clients + 1), &address, sizeof(struct sockaddr_in));
printf("client(%s:%d) connected\n", inet_ntoa(clients[1].sin_addr),
ntohs(clients[1].sin_port));

// send client B address to client A
sendto(sockfd, (void *)(clients + 1), sizeof(struct sockaddr_in), 0,
(sockaddr *)clients, sizeof(struct sockaddr_in));
// send client A address to client B
sendto(sockfd, (void *)clients, sizeof(struct sockaddr_in), 0,
(sockaddr *)(clients + 1), sizeof(struct sockaddr_in));
}
}

int main(int argc, char ** argv) {
printf("address: %s pid: %d\n", __FUNCTION__, getpid());
if (argc != 2 && argc != 4) {
printf("Usage: ./udp_hole_punching server|client <server_ip> "
"<server_port>\n");
exit(EXIT_FAILURE);
}

if (strncmp(argv[1], "server", 6) == 0) {
// server mode
server(9999);
} else {
// client mode
char * ip = argv[2];
int port = atoi(argv[3]);
client(ip, port);
}
return 0;
}

TCP打洞

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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define MAX_CONNECTION_QUEUE_SIZE 20
typedef unsigned char byte;

// UDP hole punching example, for TCP set SO_REUSEADDR
// @date 2021.12.13
// @author ourfor
// @email ourfor@qq.com

/**
* @brief UDP hold punching client
*
* @param ip server ip
* @param port server port
*/
void setSocketReuse(int sockfd) {
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuse,
sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");

#ifdef SO_REUSEPORT
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char *)&reuse,
sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
#endif
}

void client(char * ip, int port) {
int sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd == -1) {
printf("socket create failed, %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
setSocketReuse(sockfd);

struct sockaddr_in address;
socklen_t address_len = sizeof(struct sockaddr_in);
memset(&address, 0x00, sizeof(struct sockaddr_in));
address.sin_family = PF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = inet_addr(ip);

if (connect(sockfd, (struct sockaddr *)&address,
sizeof(struct sockaddr_in)) == -1) {
printf("connect server(%s:%d) failed, %s\n", ip, port, strerror(errno));
exit(EXIT_FAILURE);
}
byte buff[128] = {'H', 'E', 'L', 'L', 'O', '\0'};

struct sockaddr_in peer_address;
recv(sockfd, (void *)&peer_address, sizeof(struct sockaddr_in), 0);
recv(sockfd, (void *)buff, 1, 0);
printf("recv from server: %s\n", buff);
printf("peer address(NAT %s:%d)\n", inet_ntoa(peer_address.sin_addr),
ntohs(peer_address.sin_port));
close(sockfd);

sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (buff[0] == 'C') {
// client mode
printf("start! client mode\n");
printf("server(%s:%d)\n", inet_ntoa(peer_address.sin_addr),
ntohs(peer_address.sin_port));
if (connect(sockfd, (sockaddr *)&peer_address, address_len) == -1) {
printf("connect peer failed, %s\n", strerror(errno));
exit(EXIT_FAILURE);
}

send(sockfd, (void *)"Hello!", 6, 0);
recv(sockfd, buff, 6, 0);
buff[6] = '\0';
printf("receive from peer: %s\n", buff);
} else {
// server mode
printf("start! server mode\n");
setSocketReuse(sockfd);
struct sockaddr_in address;
memset(&address, 0x00, sizeof(struct sockaddr_in));
address.sin_family = PF_INET;
address.sin_port = peer_address.sin_port;
address.sin_addr.s_addr = INADDR_ANY;

if (bind(sockfd, (sockaddr *)&address, sizeof(struct sockaddr_in)) ==
-1) {
printf("bind socket(*:%d) failed, %s\n", port, strerror(errno));
exit(EXIT_FAILURE);
}

if (listen(sockfd, MAX_CONNECTION_QUEUE_SIZE) == -1) {
printf("listen failed, %s\n", strerror(errno));
exit(EXIT_FAILURE);
}

byte buff[10] = {0x00};
int idx = 0;

while (1) {
struct sockaddr_in address;
socklen_t address_len = sizeof(struct sockaddr_in);
int connection = accept(sockfd, (sockaddr *)&address, &address_len);
if (connection == -1) {
printf("connection failed, %s\n", strerror(errno));
continue;
}
recv(connection, buff, 6, 0);
buff[6] = '\0';
printf("receive from peer: %s\n", buff);
send(connection, (void *)"Hello!", 6, 0);
}
}
}

#define MAX_THREAD_SIZE 10
pthread_t threads[MAX_THREAD_SIZE] = {};
struct sockaddr_in clients[MAX_THREAD_SIZE] = {};
int connections[MAX_THREAD_SIZE] = {};
void * threadHandleFn(void * args) {
byte buff[128] = "Hello!";
int * connection = (int *)args;
int idx = (connection - connections) % 2;
printf("idx is %d\n", idx);
// send(connections[idx], (void *)(clients + idx), sizeof(struct
// sockaddr_in),
// 0);
return NULL;
}

void server(int port) {
int sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd == -1) {
printf("socket create failed, %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
setSocketReuse(sockfd);
struct sockaddr_in address;
memset(&address, 0x00, sizeof(struct sockaddr_in));
address.sin_family = PF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = INADDR_ANY;

if (bind(sockfd, (sockaddr *)&address, sizeof(struct sockaddr_in)) == -1) {
printf("bind socket(*:%d) failed, %s\n", port, strerror(errno));
exit(EXIT_FAILURE);
}

if (listen(sockfd, MAX_CONNECTION_QUEUE_SIZE) == -1) {
printf("listen failed, %s\n", strerror(errno));
exit(EXIT_FAILURE);
}

byte buff[10] = {0x00};
int idx = 0;

while (1) {
struct sockaddr_in address;
socklen_t address_len = sizeof(struct sockaddr_in);
int connection = accept(sockfd, (sockaddr *)&address, &address_len);
if (connection == -1) {
printf("connection failed, %s\n", strerror(errno));
continue;
}
connections[idx] = connection;

// client A
recvfrom(sockfd, buff, 10, 0, (sockaddr *)&address, &address_len);
printf("client(%s:%d) connected\n", inet_ntoa(address.sin_addr),
ntohs(address.sin_port));
memcpy((void *)(clients + idx), &address, sizeof(struct sockaddr_in));
pthread_create(threads + idx, NULL, threadHandleFn,
(void *)(connections + idx));

if (idx % 2) {
send(connections[idx], (void *)(clients + idx),
sizeof(struct sockaddr_in), 0);
send(connections[idx], (void *)"S", 1, 0);
close(connections[idx]);
send(connections[idx - 1], (void *)(clients + idx),
sizeof(struct sockaddr_in), 0);
send(connections[idx - 1], (void *)"C", 1, 0);
close(connections[idx - 1]);
}

idx++;
}
}

int main(int argc, char ** argv) {
printf("address: %s pid: %d\n", __FUNCTION__, getpid());
if (argc != 2 && argc != 4) {
printf("Usage: ./udp_hole_punching server|client <server_ip> "
"<server_port>\n");
exit(EXIT_FAILURE);
}

if (strncmp(argv[1], "server", 6) == 0) {
// server mode
server(9999);
} else {
// client mode
char * ip = argv[2];
int port = atoi(argv[3]);
client(ip, port);
}
return 0;
}

参考链接