2013-04-05 25 views
1

我已經在客戶端和服務器程序中定義了端口號。我開始接收來自客戶端的數據包的簡單udp服務器程序。服務器獲取數據包但是,當我打印客戶端信息時,端口號知道爲隨機數(51958) 如何獲取正確的端口號。即我定義的數字。未定義的端口號作爲輸出 - UDP/C/Linux

#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個插座和在服務器端,我們是在一段時間(1)迴路接收到數據發送的數據,我們如何識別客戶端發送的端口?

+0

我想你還需要發佈客戶端代碼。 – FatalError 2013-04-05 14:22:34

回答

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)); 
+0

我已經在客戶端和服務器端指定了端口號si_me.sin_port = htons(PORT); – m4n07 2013-04-05 14:31:46

+2

在客戶端代碼中,您正在設置消息的目標端口,而不是源端口。 – 2013-04-05 14:33:27

+0

我的印象是recvfrom()的第五個參數獲取客戶端詳細信息。 – m4n07 2013-04-05 14:38:08

0

您還沒有綁定的客戶端套接字連接到特定端口的端口,因此它得到了系統 - 分配端口。