inux网络编程--struct hostent结构体
来源:互联网 发布:gephi数据集下载 编辑:程序博客网 时间:2024/05/22 22:43
转自:http://blog.csdn.net/yming0221/article/details/7220478
使用这个东西,首先要包含2个头文件:
#include <netdb.h>#include <sys/socket.h>
struct hostent *gethostbyname(const char *name);
这个函数的传入值是域名或者主机名,例如" www.google.com.tw","wpc "等等。
传出值,是一个hostent的结构(如下)。如果函数调用失败,将返回NULL。
- struct hostent {
- char *h_name;
- char **h_aliases;
- int h_addrtype;
- int h_length;
- char **h_addr_list;
- };
解释一下这个结构:
其中,
char *h_name 表示的是主机的规范名。例如 www.google.com 的规范名其实是 www.l.google.com 。
char **h_aliases 表示的是主机的别名。 www.google.com 就是google他自己的别名。有的时候,有的主机可能有好几个别名,这些,其实都是为了易于用户记忆而为自己的网站多取的名字。
int h_addrtype 表示的是主机ip地址的类型,到底是ipv4(AF_INET),还是ipv6(AF_INET6)
int h_length 表示的是主机ip地址的长度
int **h_addr_lisst 表示的是主机的ip地址,注意,这个是以网络字节序存储的。千万不要直接用printf带%s参数来打这个东西,会有问题的哇。所以到真正需要打印出这个IP的话,需要调用inet_ntop()。
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
这个函数,是将类型为af的网络地址结构src,转换成主机序的字符串形式,存放在长度为cnt的字符串中。
这个函数,其实就是返回指向dst的一个指针。如果函数调用错误,返回值是NULL。
下面的例子
- #include <stdio.h>
- #include <stdlib.h>
- #include <netdb.h>
- #include <sys/socket.h>
- int main(int argc, char *argv[])
- {
- struct hostent *h;
- if (argc != 2) { /* 检查命令行 */
- fprintf(stderr,"usage: getip address\n");
- exit(1);
- }
- if ((h=gethostbyname(argv[1])) == NULL) { /* 取得地址信息 */
- error("gethostbyname");
- exit(1);
- }
- printf("Host name : %s\n", h->h_name);
- printf("IP Address : %s\n",inet_ntoa(*((struct in_addr *)h->h_addr)));
- return 0;
- }
运行结果如下
- inux网络编程--struct hostent结构体
- Linux网络编程--struct hostent结构体
- Linux网络编程--struct hostent结构体
- Linux网络编程--struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体使用
- Linux下网络相关结构体 struct hostent
- struct hostent 结构体与gethostbyname(),gethostbyaddr
- 域名和网络地址结构体---struct hostent
- 【C语言】linux网络编程—hostent结构体,gethostbyname的使用
- hostent结构体
- 强制把系统缓存写入文件 sync和fsync函数
- 在 AIX 上通过数据管道实现进程间通讯
- java堆栈 (转)
- The Linux Kernel Module Programming Guide 2.4 中文版
- setTimeout 浏览器兼容
- inux网络编程--struct hostent结构体
- Android学习笔记之TimePicker
- Java加密技术(四)
- 在SQL Server中,关于with as使用介绍
- 更改记录表CDHDR和CDPOS
- extjs的grid实现分页查看功能
- 一步一步编写最简单的linux驱动 hello world
- 编码准则与Java编译器
- java 适配器模式