1

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

4

2 回答 2

2

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

如果您有多个套接字,则可以获取与getsockname绑定的端口

if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number of the listening socket %d\n", ntohs(sin.sin_port));
于 2013-04-05T14:24:32.740 回答
0

您尚未将客户端套接字绑定到特定端口,因此它获得了系统分配的端口。

于 2013-04-06T00:23:39.660 回答