为什么 getaddrinfo( ) 总是导致段错误?

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

运行 此代码导致 getaddrinfo( ) 由于分段错误而终止程序。 编辑:检查 return getaddrinfo 的值后,错误似乎来自 getaddrinfo( ) 输入只是 www.google.com(也测试了一堆其他地址) 443(也尝试使用端口 80)

当我 运行 你的原始代码时,我得到 res0x1

问题是 buffport 字符串中有换行符 (\n)。

当换行符被剥离时,它 运行s 完成。

这是我使用的修改后的代码:

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