为什么程序将我的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;
}发布于 2019-10-24 14:47:38
根据手册:
man 3 getaddrinfo如果AI_PASSIVE标志在hints.ai_flags中指定,且节点为NULL,则返回的套接字地址将适合于绑定(2)将接受(2)连接的套接字。返回的套接字地址将包含“通配符地址”(INADDR_ANY表示IPv4地址,IN6ADDR_ANY_INIT表示IPv6地址)。通配符地址由打算在任何主机网络地址上接受连接的应用程序(通常是服务器)使用。如果节点不是NULL,则忽略AI_PASSIVE标志。
因此,0.0.0.0不是一个不正确的地址,而是通配符地址,即主机的任何地址。
https://stackoverflow.com/questions/29281614
复制相似问题