gpt4 book ai didi

c - 为什么使用 getaddrinfo、node 为 NULL、ai_flags 为 PASSIVE 会导致 IP 地址不正确?

转载 作者:行者123 更新时间:2023-11-30 17:18:05 25 4
gpt4 key购买 nike

为什么程序打印出我的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: %s\n", ip4);

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

return 0;

}

最佳答案

根据手册:

man 3 getaddrinfo

If the AI_PASSIVE flag is specified in hints.ai_flags, and node is NULL, then the returned socket addresses will be suitable for bind(2)ing a socket that will accept(2) connections. The returned socket address will contain the "wildcard address" (INADDR_ANY for IPv4 addresses, IN6ADDR_ANY_INIT for IPv6 address). The wildcard address is used by applications (typically servers) that intend to accept connections on any of the hosts's network addresses. If node is not NULL, then the AI_PASSIVE flag is ignored.

所以0.0.0.0并不是一个错误的地址,而是通配符地址,即主机的任意地址。

关于c - 为什么使用 getaddrinfo、node 为 NULL、ai_flags 为 PASSIVE 会导致 IP 地址不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29281614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com