在一個局域網上,網絡編程IP相關問題
1.怎麼搜索局域網上的計算機?
2.怎樣通過一個計算機的IP地址獲得其網卡物理地址?
例如,我的計算機為A,局域網上的有另外一台計算機為B,怎樣在A上通過B的IP地址獲取B的網卡物理地址?
如何編程用C++Builder編程實現?
//------------來自JiShiPing(JSP季世平)的代碼:---------------
#include <winnetwk.h >
#include <winsock2.h >
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void __fastcall TForm1::FormCreate(TObject *Sender)
{
TStrings *netList=new TStringList();
TListItem *NewItem;
//
ListView1- >Items- >Clear();
Screen- >Cursor=crHourGlass;
//
EnumNetResource(netList,NULL,RESOURCE_GLOBALNET,RESOURCETYPE_ANY);
for(int i=0;i <netList- >Count;i++)
{
NewItem=ListView1- >Items- >Add();
NewItem- >Caption=netList- >Strings[i];
NewItem- >SubItems- >Add(gethostip(netList- >Strings[i]));
}
Screen- >Cursor=crDefault;
delete netList;
}
//---------------------------------------------------------------------------
bool __fastcall TForm1::EnumNetResource(TStrings *rcList,LPNETRESOURCE lpNR, DWORD dwScope,DWORD dwType)
{
HANDLE hEnum = 0; // resource-handle
DWORD dwResult = WNetOpenEnum(
dwScope, // scope of enumeration
dwType, // resource types to list
0, // enumerate all resources
lpNR, // pointer to resource structure (NULL at first time)
&hEnum // handle to resource
) ;
if( dwResult != NO_ERROR ) return false;
bool bRet=true;
DWORD dwEntries = 0xFFFFFFFF ; // enumerate all possible entries
NETRESOURCE NR[1024];
DWORD dwBuffer=1024*sizeof(NETRESOURCE);
while(1)
{
dwResult = WNetEnumResource(hEnum,&dwEntries,(LPVOID)NR,&dwBuffer) ;
if( dwResult == ERROR_NO_MORE_ITEMS ) break;
else if( dwResult != NO_ERROR ) { bRet=false; break;}
for(DWORD i = 0 ; i < dwEntries ; i++ )
{
if(NR[i].dwDisplayType==RESOURCEDISPLAYTYPE_SERVER)
{
char *p=NR[i].lpRemoteName;
while(*p=='\\') p++;
if(*p) rcList- >Add(p);
}
else if((NR[i].dwUsage&RESOURCEUSAGE_CONTAINER)==RESOURCEUSAGE_CONTAINER)
{
bRet=EnumNetResource(rcList,&NR[i],dwScope,dwType);
if(bRet==false) break;
}
}
if(bRet==false) break;
}
WNetCloseEnum(hEnum) ;
return bRet;
}
//------獲取某主機的IP地址,如果主機名為空,則返回本機的名和IP地址---------
//AnsiString gethostip(AnsiString &host)
AnsiString __fastcall TForm1::gethostip(AnsiString &host)
{
WSADATA wsaData;
AnsiString IP;
WSAStartup(MAKEWORD(2,0),&wsaData);
if(host.IsEmpty())
{
char hostname[128];
if(gethostname(hostname,128)!=0) return AnsiString( " ");
host=hostname;
}
try
{
struct hostent *hp=gethostbyname(host.c_str());
if(WSAGetLastError()==WSAHOST_NOT_FOUND)
{
IP= "無法獲取 ";
return IP;
}
else
IP=inet_ntoa(*(struct in_addr*)hp- >h_addr_list[0]);
}
catch(...)
{
IP= " ";
}
WSACleanup();
return IP;
}