Get the computer name instead of the DNS name using IP adress

Viewed 42

I have the following code:

public static string GetHostname(string sIP) {
    // GetServerIP(sIP)[0] is the IP of the server
    string? sHostname = GetServerIP(sIP)[0];
    IPHostEntry host = Dns.GetHostEntry(sHostname);

    return host.HostName.ToString()!;       
}

The ip address is correct but the name returned is not (in my case) "server" but "MeinServer.speedport.ip", which is odd because the server has a static ip address. The name returned is the one used by the router.

When I use ping in cmd with the IP I get the correct name, so why not with the function?

How do I get the correct computer name and not the dns name of the router, without changing the name in the router (in this case 'server')?

1 Answers

As by docs, the behaviour is as expected:

The GetHostEntry method queries a DNS server for the IP addresses and aliases associated with an IP address.

You might want to try this: System.Environment.MachineName

which returns the NETBIOS name of the local machine. See MachineName docs.

Related