分享

通过gethostbyaddr来获取计算机的名称

 心不留意外尘 2016-07-20

http://blog.csdn.net/lllxy/article/details/1839465

2007

通过gethostbyaddr来获取计算机的名称。如下代码:

 

#include <stdio.h>
#include<winsock2.h>
#include <Ws2tcpip.h>
#pragma comment(lib,"ws2_32.lib")
int main(int argc, char* argv[])
{
    WORD wVersionRequested;
    WSADATA wsaData;
    int err;
    wVersionRequested = MAKEWORD( 2, 2 );
    err = WSAStartup( wVersionRequested, &wsaData );
    if ( err != 0 ) {
        /* Tell the user that we could not find a usable */
        /* WinSock DLL.                                  */
        return 1;
    }

    /* Confirm that the WinSock DLL supports 2.2.*/
    /* Note that if the DLL supports versions later    */
    /* than 2.2 in addition to 2.2, it will still return */
    /* 2.2 in wVersion since that is the version we      */
    /* requested.                                        */

    if ( LOBYTE( wsaData.wVersion ) != 2 ||
        HIBYTE( wsaData.wVersion ) != 2 ) {
            /* Tell the user that we could not find a usable */
            /* WinSock DLL.                                  */
            WSACleanup( );
            return 1; 
        }
    
    struct hostent *host; 
    char **alias = NULL;   
    if(argc<2) 
    { 
         fprintf(stderr,"Usage:%s hostname|ip.. a",argv[0]); 
         return 0;
    } 
    argv++; 
    for(;*argv!=NULL;argv++) 
    { 
         unsigned long ddd = inet_addr(*argv);
         if(ddd != INADDR_NONE)
         { 
           host=gethostbyaddr((char   *)&ddd,4,AF_INET); 
         }  
         else  
         { 
              host=gethostbyname(*argv);
         } 
        if(host==NULL) 
        { 
              fprintf(stderr,"No address information of %s ",*argv);           
               return 1;
        } 
        printf("Official host name %s ",host->h_name); 
        printf("Name aliases:"); 
        for(alias=host->h_aliases;*alias!=NULL;alias++) 
          printf("%s ,",*alias); 
        printf(" Ip address:"); 
        for(alias=host->h_addr_list;*alias!=NULL;alias++) 
          printf("%s ,",inet_ntoa(*(struct in_addr *)(*alias))); 
    } 
    WSACleanup();
    return 1;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多