日期:2014-05-16  浏览次数:20740 次

64位linux中使用inet_ntoa报错处理

最近一直使用linux mint 15,我用的是64位操作系统,在进行网络编程的时候,发现一个问题,请看源码:

/*get_ip_by_name.c*/

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>

int main(int argc,char *argv[])
{
	struct hostent *h;
	
	if( argc != 2 )
	{
		printf("Usage:%s hostname\n",argv[0]);
		exit(1);
	}
	if( (h=gethostbyname(argv[1])) == NULL )
	{
		herror("gethostbyname");
		exit(1);
	}
	printf("Host name: %s\n",argv[1]);
	printf("Ip address: %s\n",inet_ntop(*( (struct in_addr*)h->h_addr) ));

	return 0;
}

这段代码在以前32位 的机器上面是没有问题的,但是在我的64位机器上面就出问题了,编译时给警告:

linuxmint dns # gcc -o get_ip_by_name get_ip_by_name.c
get_ip_by_name.c: In function ‘main’:
get_ip_by_name.c:26:49: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]

警告的意思是,%s需要char *型的数据,而inet_ntoa返回的是int类型的,当我执行的时候出现了段错误!然后我man了一下,发现inet_ntoa函数在我的机器上面的返回值是int型的!这个时候需要加上#include <arpa/inet.h>,这样才能让返回值成为char *型的。当然还可以使用inet_ntop函数!