我已經在客戶端和服務器程序中定義了端口號。我開始接收來自客戶端的數據包的簡單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)迴路接收到數據發送的數據,我們如何識別客戶端發送的端口?
我想你還需要發佈客戶端代碼。 – FatalError 2013-04-05 14:22:34