C 为什么使用getaddrinfo,节点为NULL,ai_标志为被动,会导致IP地址不正确?

C 为什么使用getaddrinfo,节点为NULL,ai_标志为被动,会导致IP地址不正确?,c,C,为什么程序将我的IP地址打印为0.0.0.0?如果我指定我的IP地址,它将是正确的IP地址。我通读了手册页中关于getaddrinfo的部分,看到代码中的assign AI_PASSIVE和NULL是有效的。那么,这里出了什么问题 更新:为res和sa分配内存 #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <

为什么程序将我的IP地址打印为0.0.0.0?如果我指定我的IP地址,它将是正确的IP地址。我通读了手册页中关于getaddrinfo的部分,看到代码中的assign 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: %s\n", ip4);

    free(res); // update here
    free(sa); // update here

    return 0;

}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括“./cus_header/cus_header.h”
#定义MYPORT“30000”
#定义待办事项10
int main(int argc,char*argv[]){
结构addrinfo提示,*res;
res=malloc(sizeof(struct addrinfo));//在此处更新
字符ip4[INET_ADDRSTRLEN];
*sa中的结构sockaddr_;
sa=malloc(sizeof(struct sockaddr_in));//在此处更新
//使用getaddrinfo加载地址结构
memset(提示和提示,0,提示大小);
hits.ai_family=AF_unsec;
hits.ai_socktype=SOCK_流;
hits.ai_flags=ai_被动;
if(getaddrinfo(NULL、MYPORT、提示和res)=-1){
错误(“无法获取AI”);
}
sa=(结构sockaddr_in*)res->ai_addr;
inet_ntop(AF_inet和(sa->sin_addr),ip4,inet_ADDRSTRLEN);
printf(“IPv4地址为:%s\n”,ip4);
免费(res);//此处更新
免费(sa);//此处更新
返回0;
}

根据手册:

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


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

首先为
res
sa
@m0skit0分配内存。正如您所说,我更新了代码,但结果没有任何变化。根据您的建议,我猜getaddrinfo不会返回res的指针,是吗?