UDP套接字的端口号

port number of an UDP socket

我的 OS 是 Ubuntu 20.x 。 我有两个程序:server.c 在端口 2052 上侦听 INADDR_ANYclient.c 在同一端口的 INADDR_LOOPBACK 上本地发送 UDP 数据包。

程序运行正常,接收到的数据和IP地址与发送的一致;然而 端口号不匹配。我可以通过 netstat 看到 server.c 正在监听正确的端口 (2052),并且我将端口号转换为本地字节顺序,所以我不知道我做错了什么。

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 :

#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);
}

我的目标是在侦听(服务器)端获得正确的端口号。感谢您的帮助!

服务器正在打印的端口号是客户端的端口号。这与服务器的端口号不同。服务器然后可以使用此端口号将响应发送回客户端。

另外,发送UDP数据报时,如果不绑定特定端口,系统会随机选择一个。