我已经在客户端和服务器程序中定义了端口号。我启动了从客户端接收数据包的简单 udp 服务器程序。服务器获取数据包但是当我打印客户端信息时,端口号被称为随机数(51958)如何获取正确的端口号。即我定义的数字。
#define PORT XYZ
...
if((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
diep("socket");
memset((char *) &si_me, 0, sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_port = htons(PORT);
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(s, (struct sockaddr *) &si_me, sizeof(si_me)) == -1)
diep("bind");
for(i = 0; i < NPACK; i += 1) {
if(recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1)
diep("recvfrom()");
printf("Recieved packet from %s: %d\nData: %s\n\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
}
close(s);
/// 客户
#define PORT XYZ
if((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
diep("socket");
memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
if(inet_aton(SRV_IP, &si_other.sin_addr) == 0) {
fprintf(stderr, "inet_aton() failed\n");
exit(1);
}
{
for(i = 0; i < NPACK; i += 1) {
printf("Sending packet %d\n", index);
sprintf(buf, "This is packet%d\n", index);
;
if(sendto(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, slen) == -1)
diep("sendto()");
index++;
}
}
close(s);
更新 如果我们在 N 个套接字上发送了数据,并且在服务器端我们处于接收数据的 while(1) 循环中,我们如何识别客户端发送的端口?