socket网络编程之二:gethostbyname()和gethostbyaddr()用法

1. gethostbyname:根据主机名字得到主机信息:

    struct hostent FAR *WSAAPI gethostbyname(const char FAR * name);

  

    gethostbyaddr:根据主机地址获取主机信息:

    struct hostent FAR *WSAAPI gethostbyaddr(const char FAR * addr,
                                                                          int len,
                                                                          int type);

 

2.主机信息的结构定义:

/*
 * Structures returned by network data base library, taken from the
 * BSD file netdb.h.  All addresses are supplied in host order, and
 * returned in network order (suitable for use in system calls).
 */

struct  hostent {
        char    FAR * h_name;               /* official name of host */
        char    FAR * FAR * h_aliases;   /* alias list                    */
        short   h_addrtype;                   /* host address type    */
        short   h_length;                       /* length of address     */
        char    FAR * FAR * h_addr_list; /* list of addresses      */
#define h_addr  h_addr_list[0]          /* address, for backward compat */
}; 

 

 

3.示例程序和运行结果:

#include <winsock2.h>
#include <stdio.h>

int DisplayHostInfo(char* pName);

#pragma   comment(lib, "ws2_32.lib ")
int main()
{

    WORD wVersionRequested;
    WSADATA   wsaData;

 

    wVersionRequested = MAKEWORD( 2, 0 ); 
    if (WSAStartup(wVersionRequested , &wsaData)!=0)
    {
      printf("Winsock Initialization failed./n");
      exit(0); 
    };

    DisplayHostInfo("www.163.com");

}

 

int DisplayHostInfo(char* pName)
{
 struct hostent   *pHost=NULL;
 BYTE ucIdx =0;

 //naddr = (inet_addr("192.168.0.22"));
 //pHost =gethostbyaddr((char*)&naddr,4,AF_INET);
 pHost =gethostbyname(pName);
 if(pHost == NULL)
 {
     printf("/r/ngethostbyname error!!/n/r");
     return -1;  
 }

 printf("/r/nh_name: %s",pHost->h_name);
 for(ucIdx = 0; pHost->h_aliases[ucIdx]; ucIdx++)
 {
     printf("/r/nh_aliases[%u]: %s",ucIdx,pHost->h_aliases[ucIdx]);  
 }
 printf("/n/rh_addrtype: %u",pHost->h_addrtype);
 printf("/n/rh_length: %u",pHost->h_length);

 for(ucIdx = 0; pHost->h_addr_list[ucIdx]; ucIdx++)
 {
     printf("/r/nh_addr_list[%u]: %s/r/n",ucIdx,inet_ntoa(*(struct in_addr*)pHost->h_addr_list[ucIdx]));
 }
    return 0;
}

 

运行结果:

  DisplayHostInfo("www.163.com")获取的信息:

    h_name: 163.xdwscache.glb0.lxdns.com
    h_aliases[0]: www.163.com
    h_aliases[1]: www.cache.wangsu.netease.com
    h_aliases[2]: www.163.com.lxdns.com
    h_aliases[3]: www.163.z.lxdns.com
    h_addrtype: 2
    h_length: 4
    h_addr_list[0]: 222.88.95.169

    h_addr_list[1]: 222.88.95.137

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值