gethostbyaddr too slow
I use the following code, results are correct, but gethostbyaddr
takes around 30 seconds.
function IPAddrToName(IPAddr: string): string;
var
SockAddrIn: TSockAddrIn;
HostEnt: PHostEnt;
WSAData: TWSAData;
begin
WSAStartup($101, WSAData);
SockAddrIn.sin_addr.s_addr := inet_addr(PChar(IPAddr));
HostEnt := gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4,开发者_如何学JAVA AF_INET);
if HostEnt <> nil then
Result := StrPas(Hostent^.h_name)
else
Result := '';
end;
That's unlikely to be an issue with your code (unless WSAStartup
is particularly slow).
The first thing I would do is to output the time (preferably to the millisecond, with GetTickCount
, I think) in between each of those lines in your code, to find out exactly where the time is being spent.
The gethostbyaddr
may well have to go out to a remote DNS machine to resolve the IP address into a hostname.
If your network is set up badly, or the DNS server containing that address is in the remote regions of the Tibetan mountains for example, resolution will take some time.
From your command line, enter:
nslookup x.x.x.x
(where x.x.x.x
is the IP address you're interested in) and see how long that takes.
Based on your comment between the ruler lines below:
I am working on LAN with just 3 machines. Also that network is not connected to the internet. It takes 16 secs (+/- some millisecs) for only the line:
HostEnt := gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);
while:
GetHostByName(PChar(HostName));
is instantaneous. Below is the output of Ping (instant output) and nslookup:
c:\> ping 192.168.1.22
Reply from 192.168.1.22: bytes=32 time<1ms TTL=128 Packets:
Sent = 4, Received = 4, Lost = 0 (0% loss)
c:\> nslookup 192.168.1.22
DNS request timed out.
I think your problem is with that timeout. It appears your network is set up okay for DNS name resolution but not IP reverse resolution.
When you just type nslookup
, it should show you your DNS server that it's trying to use and this will probably give you a clue.
c:\pax> nslookup
Default Server: pax01.neveryoumind.com
Address: 9.190.230.75
It may be that resolving names to IP addresses doesn't go out through DNS but is instead handled with local information.
That's about as much help as I can give you with the current information. Since this now seems very much a SuperUser question now rather than StackOverflow, I'll nudge it over to there.
Windows attempts different ways to perform host name resolution depending on the way your hosts and LAN are configured. See http://technet.microsoft.com/en-us/library/bb727005.aspx. You should not test that code in a LAN which is not correctly configured, either using a DNS server (or at least a WINS one) or correct hosts files. Otherwise you could not get the result you'd expect in a properly configured LAN.
精彩评论