cnetwork-programmingsegmentation-faultgetaddrinfogetnameinfo

Why getaddrinfo( ) always cause segmentation fault?


#include <string.h>
#include <stdio.h>
#include <netdb.h>

int main(){
    char buff[50];
    char port[5];

    printf("Enter address to lookup: ");
    fgets(buff, 50, stdin);

    printf("Enter Port: ");
    fgets(port, 5, stdin);

    struct addrinfo* res;
    struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_flags= AI_PASSIVE;

    __auto_type error = getaddrinfo(buff, port, &hints, &res);
    if (error < 0 )
        return 4;

    printf("Host IP: %s", buff);
    error = getnameinfo(res->ai_addr, res->ai_addrlen, buff, 50, 0, 0, 0);
    if (error < 0)
        return 5;

    printf("Host IP: %s", buff);
    freeaddrinfo(res);
}

Running This code Cause getaddrinfo( ) to terminate program due to a segmentation fault. Edit: The error seems to come from getaddrinfo( ) after checking return Value of getaddrinfo the input is just www.google.com (A bunch of other address have been tested also ) 443 (tried it with port 80 as well )


Solution

  • When I run your original code, I get a res value of 0x1.

    The problem is that the buff and port strings have a newline (\n) in them.

    When the newlines are stripped it runs to completion.

    Here's the modified code I used:

    #include <string.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <netdb.h>
    
    void
    fixup(char *buf)
    {
        char *cp;
    
        cp = strchr(buf,'\n');
        if (cp != NULL)
            *cp = 0;
    }
    
    int
    main()
    {
        char buff[50];
        char port[5];
    
    #if 1
        FILE *xf = stdin;
    #else
        FILE *xf = fopen("input.txt","r");
    #endif
    
        printf("Enter address to lookup: ");
        fgets(buff, 50, xf);
        fixup(buff);
    
        printf("Enter Port: ");
        fgets(port, 5, xf);
        fixup(port);
    
        struct addrinfo *res;
        struct addrinfo hints;
    
        memset(&hints, 0, sizeof(hints));
        hints.ai_flags = AI_ALL;
    
        getaddrinfo(buff, port, &hints, &res);
        printf("res=%p\n",res);
        printf("Host IP: %s\n", buff);
    
        getnameinfo(res->ai_addr, res->ai_addrlen, buff, 50, 0, 0, NI_NUMERICHOST);
        printf("Host IP: %s\n", buff);
    
        freeaddrinfo(res);
    }