使用Windows Socket API获取局域网的电脑IP和名字

最近一直在考虑如何通过socket遍历局域网的电脑,都没有比较好的方法,下面提供一种实现方法,速度慢了点,望高手指教。

#include <stdio.h>
#include <Winsock2.h>

void main(int argc, char* argv[])
{
    // TODO: Add your control notification handler code here
    //----------------------
    // Declare and initialize variables
    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;
    }
    /* Confirm that the WinSock DLL supports 2.2.*/
    /* Note that if the DLL supports versions greater    */
    /* 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;
    }
    /* The WinSock DLL is acceptable. Proceed. */
    char hostname[100];
    int namelen = 100;
    gethostname(hostname,namelen);

    hostent* remoteHost;
    char * addr;
    remoteHost=gethostbyname(hostname);
    addr = inet_ntoa(*(struct in_addr *)(remoteHost->h_addr));

    int ip,iptmp[4];
    iptmp[0] = (*(struct in_addr *)(remoteHost->h_addr)).S_un.S_un_b.s_b1;
    iptmp[1] = (*(struct in_addr *)(remoteHost->h_addr)).S_un.S_un_b.s_b2;
    iptmp[2] = (*(struct in_addr *)(remoteHost->h_addr)).S_un.S_un_b.s_b3;
    iptmp[3] = (*(struct in_addr *)(remoteHost->h_addr)).S_un.S_un_b.s_b4;
    ip = iptmp[0]<<24 | iptmp[1]<<16 | iptmp[2]<<8 | iptmp[3];

    int i;
    int len;
    struct in_addr lan;
    for(i = 1;i<255;i++)
    {
        ip = iptmp[0]<<24 | iptmp[1]<<16 | iptmp[2]<<8 | i;
        char tmp[3];
        sprintf(tmp,"%d",i);
        printf(tmp);
        printf("\t");
        lan.S_un.S_addr = ntohl(ip);
        addr = inet_ntoa(lan);
        len = ntohl(ip);
        remoteHost=gethostbyaddr((char *)&len,4,AF_INET);
        if(NULL != remoteHost)
        {
            printf("%s\t%s",addr,remoteHost->h_name);
        }
        printf("\n");
    }
    WSACleanup();
    return;
}

posted @ 2008-07-03 00:09  szhy222  阅读(1933)  评论(4编辑  收藏  举报