欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

主机名称处理函数

程序员文章站 2022-07-14 20:33:09
...
#include <netdb.h>

struct hostent	*gethostbyaddr (const void *, socklen_t, int);
struct hostent	*gethostbyname (const char *);

hostent结构体:

/* Different from the linux versions - note the shorts.. */
struct	hostent {
	const char	*h_name;	/* official name of host */
	char	**h_aliases;	/* alias list */
	short	h_addrtype;		/* host address type */
	short	h_length;		/* length of address */
	char	**h_addr_list;	/* list of addresses from name server */
#define	h_addr	h_addr_list[0]	/* address, for backward compatiblity */
};

主机名称处理函数
主机名称处理函数
1、根据主机名获取主机信息

struct hostent * gethostbyname (const char *name)

Description:
The gethostbyname function returns information about the host named name. If the lookup fails, it 
 returns a null pointer. 

示例:

	struct hostent* ht = NULL;
	char name[] = "www.sina.com";
	ht = gethostbyname(name);

2、根据IP地址获取主机信息

struct hostent * gethostbyaddr (const char *addr, size_t length, int format)

Description:
The gethostbyaddr function returns information about the host with Internet address addr. The 
 parameter addr is not really a pointer to char - it can be a pointer to an IPv4 or an IPv6 address. The 
 length argument is the size (in bytes) of the address at addr. format specifies the address format; for 
 an IPv4 Internet address, specify a value of AF_INET; for an IPv6 Internet address, use AF_INET6. 

If the lookup fails, gethostbyaddr returns a null pointer. 

示例:

	struct hostent* ht1 = NULL;
	char ipaddr[] = "192.168.1.1";
	ht1 = gethostbyaddr(ipaddr, sizeof(ipaddr), AF_INET);

线程安全性:gethostbyname和gethostbyaddr是不可冲入的,调用结束后要及时将结果取出;目前已有线程安全的替代版本,并且适用于IPv4和IPv6,即getaddrinfo和getnameinfo。

相关标签: UNIX网络编程