-1

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

mateass
  • 105
  • 2
  • 11

2 Answers2

4

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

user253751
  • 57,427
  • 7
  • 48
  • 90
1

The last argument to your recvfrom() call is incorrect. It is supposed to be a pointer of type socklen_t *, pointing to a location where the address size is initially stored. The function modifies the value stored there to reflect the actual size of the address structure, as it wrote it or as it would have written it if the initial size were large enough. You instead pass the actual size, which must be implicitly converted to a pointer. Your compiler ought to be warning you about that.

Given that the program is not crashing, recvfrom() must be successfully reading a value from the address pointed to by the converted integer, and successfully writing a value there. Quite possibly, it is reading the value 0.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157