为什么在node为NULL、ai_flags为PASSIVE的情况下使用getaddrinfo会导致IP地址不正确



为什么程序将我的IP地址打印为0.0.0.0?如果我指定我的IP地址,它将是正确的IP。我阅读了手册页中关于getaddrinfo的部分,发现代码中指定AI_PASSIVE和NULL是有效的。那么,这里怎么了?

更新:为res和sa 分配内存

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include "../cus_header/cus_header.h"
#define MYPORT "30000"
#define BACKLOG 10

int main(int argc, char *argv[]){
    struct addrinfo hints, *res;
    res = malloc(sizeof(struct addrinfo)); // update here
    char ip4[INET_ADDRSTRLEN];
    struct sockaddr_in *sa;
    sa = malloc(sizeof(struct sockaddr_in)); // update here
    // load up address struct with getaddrinfo
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    if(getaddrinfo(NULL, MYPORT, &hints, &res) == -1){
        error("Cannot get AI");
    }
    sa = (struct sockaddr_in*)res->ai_addr;
    inet_ntop(AF_INET, &(sa->sin_addr), ip4, INET_ADDRSTRLEN);
    printf("The IPv4 address is: %sn", ip4);
    free(res); // update here
    free(sa); // update here
    return 0;
}

根据手册:

man 3 getaddrinfo

如果在hints.AI_flags中指定了AI_PASSIVE标志,并且节点为NULL,则返回套接字地址将适合于绑定(2)将接受(2)连接的套接字。返回的套接字地址将包含"通配符地址"(IPv4的INADDR_ANY地址、用于IPv6地址的IN6ADDR_ANY_INIT)。通配符地址由应用程序使用(通常是服务器)打算接受任何主机网络上的连接地址。如果节点不为NULL,则AI_PASSIVE标志将被忽略。

因此0.0.0.0不是一个错误的地址,而是通配符地址,即主机的任何地址。

最新更新