简体   繁体   English

UDP 套接字的端口号

[英]port number of an UDP socket

My OS is Ubuntu 20.x .我的操作系统是 Ubuntu 20.x 。 I have two programs : server.c that listens to INADDR_ANY on the port 2052 and client.c that sends UDP packets locally on INADDR_LOOPBACK at the same port.我有两个程序: server.c在端口2052上侦听INADDR_ANYclient.c在同一端口的INADDR_LOOPBACK上本地发送 UDP 数据包。

The programs works fine and the received data and IP address match the sent ones;程序运行良好,接收到的数据和 IP 地址与发送的数据和 IP 地址匹配; however the port numbers do not match.但是端口号不匹配。 I can see with netstat that server.c is listening at the correct port ( 2052 ) and I convert the port number to the local endianess so I have no idea what I'm doing wrong.我可以通过netstat看到server.c正在侦听正确的端口 ( 2052 ) 并且我将端口号转换为本地字节序,所以我不知道我做错了什么。

server.c : server.c

#define MY_PORT 2052

int main (void)
{
    int socket_descriptor = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in server_socket = {.sin_addr = {.s_addr = htonl(INADDR_ANY)}, .sin_port = htons(MY_PORT), .sin_family = AF_INET, .sin_zero = {0}};

    bind(socket_descriptor, (struct sockaddr *) &server_socket, sizeof(server_socket));


    char client_msg[SIZE + 1] = {0};
    struct sockaddr_in client_socket;
    socklen_t addrlen = sizeof(client_socket);


    ssize_t received_bytes = recvfrom(socket_descriptor, client_msg, SIZE, 0, (struct sockaddr*) &client_socket, &addrlen);

    // this prints the data sent as expected : 
    printf("received %ld bytes of data : data was %s\n", received_bytes, client_msg);
    // this prints 127.0.0.1 as expected :
    printf("the client IP address was %s\n", inet_ntop(AF_INET, &client_socket.sin_addr, (char [INET_ADDRSTRLEN]) {0},  INET_ADDRSTRLEN));
    // this prints the WRONG port :
    printf("the port was %d\n", ntohs(client_socket.sin_port));
    
    close(socket_descriptor);
}

client.c : client.c

#define MY_PORT 2052

int main (void)
{
    int socket_descriptor = socket(AF_INET, SOCK_DGRAM, 0);

    struct sockaddr_in client_socket = {.sin_port = htons(MY_PORT), .sin_family = AF_INET, .sin_addr = {.s_addr = htonl(INADDR_LOOPBACK)}, .sin_zero = {0}};

    char buffer[SIZE] = "this is a test message";

    sendto(socket_descriptor, buffer, SIZE, 0, (struct sockaddr*)&client_socket, sizeof(client_socket));

    close(socket_descriptor);
}

My goal is to get the correct port number on the listening (server) side.我的目标是在侦听(服务器)端获得正确的端口号。 Thanks for your help !谢谢你的帮助 !

The port number that the server is printing is the client's port number.服务器打印端口号是客户端的端口号。 This is different from the server's port number.这与服务器的端口号不同。 The server can then use this port number to send a response back to the client.然后服务器可以使用此端口号将响应发送回客户端。

Also, when sending a UDP datagram, if you don't bind to a specific port the system will chose one at random.此外,在发送 UDP 数据报时,如果您未绑定到特定端口,系统将随机选择一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM