我正在开展一个很酷的项目,我需要从服务器向客户端发送100,000个UDP数据包,数据包到数据包的延迟为10毫秒。服务器是具有公共IP地址的Debian服务器。客户端是具有LTE USB调制解调器的其他Debian PC。客户端没有公共IP地址,并且知道我的服务器的公共IP地址。我的4G / LTE提供商不向其客户提供公共IP地址。 我需要构建一个稳定的UDP套接字连接,但我正在努力保持套接字连接活着。
有人能帮助我吗?
THX
最好的问候
/**** CLIENT ****/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define PORT 20009
int main()
{
int sock;
int size;
int nbytes, flags;
int i;
int a = 0;
char * cp;
char buffer[] = "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
struct sockaddr_in target_pc, me;
sock = socket(PF_INET,SOCK_DGRAM,0);
if(sock < 0)
{
printf("socket error = %d\n", sock);
return -1;
}
target_pc.sin_family = PF_INET;
target_pc.sin_port = htons(PORT);
me.sin_family = PF_INET;
me.sin_port = htons(0);
me.sin_addr.s_addr = htonl(INADDR_ANY);
i = bind(sock, (struct sockaddr *) &me, sizeof(me));
if( i < 0)
{
printf("bind result: %d\n", i);
return -1;
}
nbytes = 200;
char str_addr[] = "155.55.25.25";
target_pc.sin_addr.s_addr = inet_addr(&str_addr[0]);
while(1)
{
nbytes = strlen(buffer);
flags = 0;
sendto(sock, (char *) buffer, nbytes,flags,(struct sockaddr *)&target_pc,sizeof(target_pc));
int addrlen = sizeof(target_pc);
size = recvfrom(sock, buffer, nbytes, flags, (struct sockaddr *)&target_pc,&addrlen);
if((size > 0) && (size < 200))
{
buffer[size] = '\0';
i = puts((char *) buffer);
}
printf("%i --- Size: %lu\n", a, sizeof(buffer));
a = a + 1;
}
return 0;
}
在我的服务器代码下面:
/*** SERVER ***/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define PORT 20009
void SleepMs(int ms)
{
usleep(ms*1000); //convert to microseconds
return;
}
int main()
{
int sock;
int size;
int nbytes, flags;
socklen_t addrlen;
int i;
char buffer[100];
char buffer2[] = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890\0";
struct sockaddr_in server;
struct sockaddr_in from;
sock = socket(AF_INET,SOCK_DGRAM,0);
if(sock < 0)
{
printf("socket error = %d\n", sock);
return -1;
}
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(PORT);
i = bind(sock, (struct sockaddr *) &server, sizeof(server));
if( i < 0){
printf("bind result: %d\n", i);
return -1;
}
else{
printf("Simple UDP server is ready!\n");
}
nbytes = 200;
flags = 0;
while(1)
{
addrlen = sizeof(from);
size = recvfrom(sock, buffer, nbytes, flags, (struct sockaddr *)&from, &addrlen);
if((size > 0) && (size < 200))
{
buffer[size] = '\0';
i = puts((char *) buffer);
}
printf("\n");
sock = socket(PF_INET,SOCK_DGRAM,0);
if(sock < 0)
{
printf("socket error = %d\n", sock);
return -1;
}
sendto(sock, buffer2, nbytes, flags, (struct sockaddr *)&from,addrlen);
SleepMs(10); // Packet-to-Packet Delay Time
}
return 0;
}
答案 0 :(得分:-2)
在这种情况下,您可以使用服务器的IP进行连接192.168.1.2
server.sin_addr.s_addr = inet_addr(“ 192.168.1.2”);
在两个代码中都使用