我有以下代码来获取主机名和IP地址,
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h> /* This is the header file needed for gethostbyname() */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc,char *argv[])
{
struct hostent *he;
if (argc!=2){
printf("Usage: %s <hostname>\n",argv[0]);
exit(-1);
}
if ((he=gethostbyname(argv[1]))==NULL){
printf("gethostbyname() error\n");
exit(-1);
}
printf("Hostname : %s\n",he->h_name); /* prints the hostname */
printf("IP Address: %s\n",inet_ntoa(*((struct in_addr *)he->h_addr))); /* prints IP address */
}
但是我在编译期间收到警告:
$cc host.c -o host host.c: In function ‘main’: host.c:24: warning: format ‘%s’ expects type ‘char *’,but argument 2 has type ‘int’
然后在运行代码时出现分段错误:
./host 192.168.1.4 Hostname : 192.168.1.4 Segmentation fault
代码中的错误是什么?
解决方法
关于printf格式不匹配的警告是一个重要的警告.
在这种情况下,它是因为编译器认为函数inet_ntoa返回一个int,但您指定期望格式字符串中的字符串.
在这种情况下,它是因为编译器认为函数inet_ntoa返回一个int,但您指定期望格式字符串中的字符串.
inet_ntoa的错误返回类型是旧C规则的结果,该规则声明如果您尝试使用没有事先声明的函数,则编译器必须假定该函数返回一个int并且取一个未知(但固定)的数字参数.
假定的返回类型与函数的实际返回类型之间的不匹配会导致未定义的行为,这表现为您的案例中的崩溃.
解决方案是包含inet_ntoa的正确标头.