求局域网内用ip地址获取计算机名称方法?
求代码。
局域网内用IP地址(ip已知)获取计算机名称方法?
[解决办法]
用WinSock2 API函数getnameinfo
int WSAAPI getnameinfo(
__in const struct sockaddr FAR *sa,
__in socklen_t salen,
__out char FAR *host,
__in DWORD hostlen,
__out char FAR *serv,
__in DWORD servlen,
__in int flags
);
MSDN里的例子:
//-----------------------------------------
// Call getnameinfo
dwRetval = getnameinfo((struct sockaddr *) &saGNI,
sizeof (struct sockaddr),
hostname,
NI_MAXHOST, servInfo,
NI_MAXSERV, NI_NUMERICSERV);
if (dwRetval != 0) {
printf("getnameinfo failed with error # %ld\n",
WSAGetLastError());
} else {
printf("getnameinfo returned hostname = %s\n", hostname);
}
[解决办法]
//用这个函数就可以了!
AnsiString __fastcall TForm1::GetComputerNameByAddr ( AnsiString IP )
{
hostent * ClientHost;
DWORD InetAddr = inet_addr ( IP.c_str() );
ClientHost = gethostbyaddr ( (char*)&InetAddr, IP.Length(), PF_INET );
return ClientHost-> h_name;
}
void __fastcall TForm1::Button2Click(TObject *Sender)
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 0 );
err=WSAStartup(wVersionRequested,&wsaData );
if(err!=0)
{
WSACleanup();
return;
}
String strIPAddr = "127.0.0.1 ";
struct hostent *hostname;
unsigned int addr;
addr = inet_addr((char FAR*)(strIPAddr.c_str()));
hostname=gethostbyaddr((char *)&addr,4,AF_INET);
if(hostname)
ShowMessage(hostname-> h_name);
WSACleanup();
}