您尚未登录。

#1 2020-07-18 19:15:10

beginner
会员
注册时间: 2019-10-07
帖子: 256

inet_ntop获得的ip不正确

以下代码,是先打开文件,然后把得到的ip地址写进去再关闭文件。

#include <stdio.h>
#include <netdb.h>
#include <string.h>
#define MAXBYTE 0xff
int main(int argc, char *agv[]){
	const char hostName[][MAXBYTE] = { "github.com", "github.global.ssl.fastly.net", "codeload.github.com" };
	FILE *fp = fopen("/etc/hosts", "w");
	if(!fp){
		perror("open file /etc/hosts error");
		return -1;
	}
	for(int i = 0; i < 3; ++i){
		char **phe = NULL;
		char destIp[MAXBYTE];
		struct hostent *he = gethostbyname(hostName[i]);
		inet_ntop(he->h_addrtype,*he->h_addr_list,destIp,sizeof(destIp));
		char content[MAXBYTE * 2];
		sprintf(content, "%s %s\n", destIp, hostName[i]);
		fwrite(content, strlen(content), 1, fp);
		printf("%s", content);
	}
	fclose(fp);
        return 0;
}

这是提这个问题时程序的输出

13.250.177.223 github.com
173.252.102.16 github.global.ssl.fastly.net
54.251.140.56 codeload.github.com

我尝试过www.baidu.com这个域名,输出是39.156.69.79 220.181.38.148,分成两次输出。
以上ip除了www.baidu.com外,都和IPAddress得到的结果不一样,这是为何?

离线

#2 2020-07-18 19:32:18

依云
会员
所在地: a.k.a. 百合仙子
注册时间: 2011-08-21
帖子: 8,443
个人网站

Re: inet_ntop获得的ip不正确

重复帖。

离线

页脚