gpt4 book ai didi

c - 查找主机名和 IP 地址时出现段错误

转载 作者:太空狗 更新时间:2023-10-29 17:17:04 26 4
gpt4 key购买 nike

我有以下代码用于获取主机名和 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

代码中有什么错误?

最佳答案

我有一个类似的代码(如果不一样的话)并且它在我们学校实验室的机器上编译得很好,但是当我在家里的机器上编译它时,它有同样的错误(我没有编辑代码).我阅读了 inet 的手册页, 发现我少了一个头文件,即 #include <arpa/inet.h> .将该 header 添加到我的 C 程序后,它编译并运行良好。

关于c - 查找主机名和 IP 地址时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2906845/

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