我知道已经回答了相关问题,但我没有设法解决我的问题。
我有一个简单的 UDP 客户端-服务器应用程序。客户端和服务器看起来都不错,但是服务器没有从客户端接收数据包,它只是无限接收网络 ID 192(或者客户端可能没有正确发送数据包)。
我似乎无法弄清楚问题所在,地址和端口都可以,我没有任何防火墙,我什至为端口添加了一个例外,只是为了确定。如果我启动服务器,我可以看到它在正确的端口(netstat -a -s -p udp)上监听。你能告诉我什么是错的吗?
这是我的服务器代码:
/*.. includes */
#define PORT 8888
#define NPACK 10
#define MAXLEN 100
void signalError(char* s){
perror(s);
exit(1);
}
int main()
{
struct sockaddr_in struct_srv, struct_client;
int s,i,cod, numbytes;
size_t clientSize;
int32_t nr;
int32_t sir1[MAXLEN], sir2[MAXLEN], sirComune[MAXLEN], nrEl1, nrEl2, nrComune;
//Creating the socket:
s = socket(PF_INET, SOCK_DGRAM, 0);
if(s==-1) signalError("Error while creating socket!");
memset(&struct_srv, 0, sizeof(struct_srv));
struct_srv.sin_family = AF_INET;
struct_srv.sin_addr.s_addr = htonl(INADDR_ANY);
struct_srv.sin_port = htons(PORT);
s = bind(s, (struct sockaddr*) &struct_srv, sizeof(struct_srv));
if(s==-1) signalError("Bind error. Port is already in use!");
//receive packets:
nrEl1 = -1;
char buf[MAXLEN];
printf("Accepting packets:\n");
//for(i=0;i<NPACK;i++) {
for(;;) {
//Receive packets from client:
clientSize = sizeof(struct_client);
numbytes = recvfrom(s, buf, MAXLEN - 1, 0,
(struct sockaddr*) &struct_client, &clientSize);
buf[numbytes] = '\0';
printf("Packet is %d long.\n", numbytes);
printf("Packet contains %s:\n", buf);
sleep(3);
}
close(s);
return 0;
}
我的客户代码:
/* includes */
#define SRV_IP "127.0.0.1"
#define NPACK 100
#define MAXLEN 100
#define PORT 8888
void signalError(char* s){
perror(s);
exit(1);
}
int main(void)
{
struct sockaddr_in struct_client;
int s, i, result, size_client = sizeof(struct_client);
int32_t nr, sir1[MAXLEN], sir2[MAXLEN];
s = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(s==-1) signalError("Erorr creating socket!");
memset((char*) &struct_client, 0, sizeof(struct_client));
struct_client.sin_family = AF_INET;
struct_client.sin_addr.s_addr = htonl(INADDR_ANY);
struct_client.sin_port = htons(PORT);
if(inet_aton(SRV_IP, &struct_client.sin_addr)==0) {
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
char buf[MAXLEN];
int len;
for(i=0;i<NPACK;i++) {
printf("Give packet %d:\n", i+1);
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf)-1] = '\0';
printf("I've read %s\n", buf);
printf("Sending packet %d\n", i+1);
result = sendto(s, buf, sizeof(buf)+1, 0,
(struct sockaddr*) &struct_client, size_client);
if(result==-1) signalError("Error sending packets!");
}
close(s);
return 0;
}