ai_next 链表中 C 空指针检查失败

C null pointer check fails in ai_next linked list

背景:我正在关注 Beej's Guide to Network Programming 如何使用 C 套接字监听和接受传入连接。

问题:我遇到的问题是在遍历要侦听的地址链表时出现分段错误。我会检查下一个结构是否为空,但这不起作用。

我试过的:在这段代码和我以前写的工作示例之间,我只能说出一个区别,即这些是我自己计算机上的地址与另一个主机。我也查看了 getaddrinfo 的手册页,据我所知,我正在遵循示例实现。

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>

#define MYPORT "6161"

int main() {
    struct addrinfo hints, *res;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_family = AI_PASSIVE;

    getaddrinfo(NULL, MYPORT, &hints, &res);

    struct addrinfo *addr;
    for (addr = res; addr != NULL; addr = addr->ai_next) {
        printf("Here's one addr!");
    }

    return 0;
}

我发现问题了...

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>

#define MYPORT "6161"

int main() {
    struct addrinfo hints, *res;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_family = AI_PASSIVE;

    getaddrinfo(NULL, MYPORT, &hints, &res);

    struct addrinfo *addr;
    for (addr = res; addr != NULL; addr = addr->ai_next) {
        printf("Here's one addr!");
    }

    return 0;
}

这是您的代码。

这是更正后的代码:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>

#define MYPORT "6161"

int main() {
    struct addrinfo hints, *res;

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    getaddrinfo(NULL, MYPORT, &hints, &res);

    struct addrinfo *addr;
    for (addr = res; addr != NULL; addr = addr->ai_next) {
        printf("Here's one addr!");
    }

    return 0;
}

您刚刚写了两次 ai_family,因此将 AI_PASSIVE 分配给 hints.ai_family 而不是 hints.ai_flags

我尝试了更正后的代码,它工作正常。