gpt4 book ai didi

c - 未定义的端口号作为输出 - UDP/C/Linux

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:24:13 26 4
gpt4 key购买 nike

我已经在客户端和服务器程序中定义了端口号。我启动了从客户端接收数据包的简单 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) 循环中接收数据,我们如何识别客户端发送的端口?

最佳答案

我认为它实际上是正确的端口号,因为您打印的是客户端的源端口(如果没有指定,客户端主机使用随机的免费端口)而不是目标端口服务器也在监听哪个

如果你有多个套接字,你可以获得与getsockname绑定(bind)的端口

if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
perror("getsockname");
else
printf("port number of the listening socket %d\n", ntohs(sin.sin_port));

关于c - 未定义的端口号作为输出 - UDP/C/Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15836314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com