Search code examples
csocketsunixudpdatagram

recvfrom() always return zero remote address


I'm writing a simple udp server application and i ran into an error when i try to get the address of the remote connecting user.

while(run == 1) {
    struct sockaddr_in client_addr;
    char message[1024];
    int len = recvfrom(sockfd, message, 1024, 0, (struct sockaddr*)&client_addr, sizeof client_addr);

    printf("Received request from: %s#%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
}

It always return the remote address: 0.0.0.0#0


Solution

  • If you read the documentation for recvfrom, you'll see the last parameter is a pointer to a socklen_t holding the size of the address.

    So it should be:

    socklen_t client_addr_len = sizeof client_addr;
    int len = recvfrom(....., (struct sockaddr*)&client_addr, &client_addr_len);
    

    After calling recvfrom, client_addr_len will hold the actual address length (which could be smaller than the buffer, in theory, if it not an AF_INET address).