0
#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( ) 由于分段错误而终止程序。编辑:检查输入的返回值后,错误似乎来自 getaddrinfo()getaddrinfo只是 www.google.com(还测试了一堆其他地址)443(也用端口 80 尝试过)

4

1 回答 1

1

当我运行您的原始代码时,我得到一个res.0x1

问题是buffandport字符串中有一个换行符 ( \n)。

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

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

#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);
}
于 2020-07-16T01:47:11.030 回答