Search code examples
c#dnsnetwork-programming

C# - Dns.GetHostEntry: host name is empty or not correct


My PC is connected to a LAN which gateway is 80.0.0.1 When I use this code:

IPHostEntry hostEntry = Dns.GetHostEntry("80.0.0.1");
Var name = hostEntry.HostName;

it gives me the name of a global Internet domain (hari-core-2a-xe-800-0.network.virginmedia.net), not the name of my local host. How can I get the right name of the local host. I know that there are reserved domains like 10.0.x.x that can be used with LANs, but I don't want to change the LAN gateway. If I can change it in my LAN, I can't force all users of my application to change theirs if they have similar conflictions. Is there any work around?

Edit: I changed the LAN to 9.0.0.1 for testing. Dns.GetHostEntry threw "No such host is known" exception. It fails to get the name of the AP. and android devices connected to the LAN. Any solution? Note: Advanced IP Scanner also can't get the names of the devices. It displays tha IP ot each device as a name.


Solution

  • The solution that works for me:

    1. I changed the gateway IP for my LAN to 10.0.1.1 to avoid conflictions.
    2. I use DNS.GetHostEntry to get the name.
    3. If name is empty (happens in LAN with some AP models) or equals to the IP address, I suppose this is the IP of an AP or a router. I will try to connect to the webpage http:\[ip] and use the title of the webpage as a name (The title will be the device model). This works with devices that displays login page. If the device wants to supply the username and password with the request, an WebException occurs and I can get the response.Headers["WWW-Authenticate"] which contains the string: Basic realm="X", where X is a string that describes the device.
    4. If name is still empty, I get the MAC address show it as a name.

    You can find the code (C# & VB.NET) in the PingThread Class in the IPScanner Applicationm here: http://www.mediafire.com/file/1fku7fz7ytr8p59/IPScanner.zip