局域网的IP扫描

来源:互联网 发布:淘宝联盟上个月钱不见 编辑:程序博客网 时间:2024/04/27 20:50

#include <vcl.h>
#include <winsock2.h>
//---------------------------------------------------------------------------
bool    GetLanIPAddress(TStrings *strings)
{
    int             originCount = strings->Count;
    struct hostent  *host;
    struct in_addr  *ptr;
    DWORD           dwScope = RESOURCE_CONTEXT;
    HANDLE          hEnum;
    NETRESOURCE     *netResource = NULL;
    WSADATA         wsaData;
    int             a, b, c, d;

    WNetOpenEnum(dwScope, NULL, NULL, NULL, &hEnum);
    WSAStartup(MAKEWORD(1,1), &wsaData);
    if ( hEnum ) {
        DWORD Count = 0xFFFFFFFF;
        DWORD BufferSize = 2048;
        LPVOID Buffer = new char[2048];
        WNetEnumResource( hEnum, &Count, Buffer, &BufferSize );
        netResource = (NETRESOURCE*)Buffer;
        char szHostName[200];
        unsigned int i;
        for( i=0; i<BufferSize/sizeof(NETRESOURCE); i++, netResource++ )
        if( netResource->dwUsage    == RESOURCEUSAGE_CONTAINER  &&
            netResource->dwType     == RESOURCETYPE_ANY         ) {

            if( netResource->lpRemoteName ) {
                String strFullName  = netResource->lpRemoteName;
                if( strFullName.Pos("////") == 1 )
                    strFullName = strFullName.SubString(3,strFullName.Length()-2);

                gethostname( szHostName, strlen(szHostName) );
                host = gethostbyname(strFullName.c_str());

                if( host == NULL)
                    continue;

                ptr = (struct in_addr *)host->h_addr_list[0];

                a   = ptr->S_un.S_un_b.s_b1;    //172
                b   = ptr->S_un.S_un_b.s_b2;    //22
                c   = ptr->S_un.S_un_b.s_b3;    //106
                d   = ptr->S_un.S_un_b.s_b4;    //213

                strings->Add(Format("%d.%d.%d.%d",ARRAYOFCONST((a,b,c,d))));
            }
        }

        delete Buffer;
        WNetCloseEnum( hEnum );
    }

    WSACleanup();
    return(strings->Count > originCount);
}
//---------------------------------------------------------------------------

原创粉丝点击