域名和网络地址结构体---struct hostent
来源:互联网 发布:ipad监控软件 编辑:程序博客网 时间:2024/05/02 03:03
该结构体定义如下:
struct hostent{ char *h_name; //主机名,即官方域名 char **h_aliases; //主机所有别名构成的字符串数组,同一IP可绑定多个域名 int h_addrtype; //主机IP地址的类型,例如IPV4(AF_INET)还是IPV6 int h_length; //主机IP地址长度,IPV4地址为4,IPV6地址则为16 char **h_addr_list; /* 主机的ip地址,以网络字节序存储。若要打印出这个IP,需要调用inet_ntoa()。*/};
使用gethostbyname函数可以利用字符串格式的域名获得IP地址,并且将地址信息装入 hostent 域名结构体。该函数定义如下:
具体示例如下:
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <arpa/inet.h>#include <netdb.h>void error_handling(char *message);int main(int argc, char *argv[]){ int i; struct hostent *host; if(argc!=2) { printf("Usage : %s <addr>\n", argv[0]); exit(1); } host=gethostbyname(argv[1]); if(!host) error_handling("gethost... error"); printf("Official name: %s \n", host->h_name); for(i=0; host->h_aliases[i]; i++) printf("Aliases %d: %s \n", i+1, host->h_aliases[i]); printf("Address type: %s \n", (host->h_addrtype==AF_INET)?"AF_INET":"AF_INET6"); for(i=0; host->h_addr_list[i]; i++) printf("IP addr %d: %s \n", i+1, inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));//!!! return 0;}void error_handling(char *message){ fputs(message, stderr); fputc('\n', stderr); exit(1);}
由于hostent结构体成员h_addr_list指向字符串指针数组,也就是说数组里元素 char *
, 但是 inet_ntoa() 需要的是 struct in_addr*
(存放IPV4地址信息),所以要使用struct in_addr*
进行强制类型转换。
那么为什么hostent结构体的h_addr_list里的元素是 char *
, 而不直接是 struct in_addr*
?答案如下:
反之,如果要利用IP地址获得域名,可以使用函数gethostbyaddr,定义如下:
0 0
- 域名和网络地址结构体---struct hostent
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体
- struct hostent结构体使用
- struct hostent 结构体与gethostbyname(),gethostbyaddr
- Linux网络编程--struct hostent结构体
- inux网络编程--struct hostent结构体
- Linux网络编程--struct hostent结构体
- Linux网络编程--struct hostent结构体
- hostent和in_addr结构体
- Linux下网络相关结构体 struct hostent
- gethostbyname和struct hostent详解
- 【C语言】leetcode 67. Add Binary
- 泛型应用
- 29 leetcode - Divide Two Integers
- git学习笔记
- Android利器之Service
- 域名和网络地址结构体---struct hostent
- 三台机器搭建Hadoop集群
- 浅析LDA-主题模型
- CSS基础
- 三种特征选择方法及Spark MLlib调用实例(Scala/Java/python)
- Sparse Matrix --- (1) Blocks
- 用栈和递归求解迷宫问题
- 数据表中既有utf8,又有gbk编码,保存的时候很是latin1的格式
- android自动拉伸位图即.9图