csocketssegmentation-faultrecvfrom

segmentation fault(core dump created) in recvfrom


I was writing a simple C code to create a lisening socket. The code is teh following:

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>

void main() {
    struct sockaddr_in server;
    struct sockaddr_in client;
    int clientlen;
    char buf[1500];

    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

    memset((char *)&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    server.sin_port = htons(9090);

    if(bind(sock, (struct sockaddr *) &server, sizeof(server)) < 0)
        error("ERROR on binding");

    while(1) {
        bzero(buf, 1500);
        recvfrom(sock, buf, 1500-1, 0, (struct sockaddr *) &client, &clientlen);
        printf("%s\n", buf);
        printf("%d - %s\n", client.sin_port, client.sin_addr.s_addr);
    }
    close(sock);
}

The code compile with no problem but when I connect to the server with a client using netcat:

nc -u 10.0.2.4 9090

and I send some message, the message are replied and then I get the error. DO someone knows why I get this behaviour? Thank you.


Solution

  • There are two main issues here. First, clientlen is expected to contain the size of the address structure before recvfrom is called, but it is uninitialized. So set it as follows:

    int clientlen = sizeof(client);
    

    Second, you're using %s to print client.sin_addr.s_addr but that field is not a string. You should use inet_ntoa to convert a struct inaddr_t to a string:

    printf("%d - %s\n", ntohs(client.sin_port), inet_ntoa(client.sin_addr));