欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

gethostbyname函数

发布时间:2025/6/15 编程问答 36 豆豆
生活随笔 收集整理的这篇文章主要介绍了 gethostbyname函数 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

            gethostbyname()返回对应于给定主机名的包含主机名字和地址信息的hostent结构的指针,它是协议相关的,只能用于IPv4。getaddrinfo也有类似功能,但是它是协议相关的,先看看hostent结构体。

struct hostent {char *h_name; //主机名char **h_aliases; //主机别名(指向到虚拟主机的域名)int h_addrtype; //主机IP地址类型int h_length; //主机IP地址长度,对于IPv4是四字节char **h_addr_list; //主机IP地址列表 };#define h_addr h_addr_list[0]
实践代码:

#include <stdio.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h>//头文件没有包含全可能会莫名的core dumpint main() {char szWeb[]="www.baidu.com";struct hostent *pHost=gethostbyname(szWeb);//完成主机名到域名的解析 char *IP=inet_ntoa(*((struct in_addr *)pHost->h_addr));printf("ip=%s\n",IP);char *IP1=inet_ntoa(*((struct in_addr *)pHost->h_addr_list[1]));printf("IP1=%s\n",IP1);char *name=pHost->h_name;printf("name=%s\n",name);char *aliases=pHost->h_aliases[0];printf("aliases=%s\n",aliases);int type=pHost->h_addrtype;printf("type=%d\n",type);int length=pHost->h_length;printf("length=%d\n",length);return 0; }

编译运行:

ip=14.215.177.38
IP1=14.215.177.39
name=www.baidu.com
aliases=(null)
type=2
length=4






总结

以上是生活随笔为你收集整理的gethostbyname函数的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。