通過gethostbyaddr來擷取電腦的名稱

來源:互聯網
上載者:User

通過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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.