csocketsudpportsockaddr-in

port number of an UDP socket


My OS is 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.

The programs works fine and the received data and IP address match the sent ones; 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.

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

My goal is to get the correct port number on the listening (server) side. Thanks for your help !


Solution

  • 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.