2

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')?

Novellist
  • 21
  • 3
  • It's doing a `PTR` reverse lookup, which in your case returns the public DNS name for that IP address, it has no knowledge of your internal server unless it's querying your internal DNS – Charlieface Sep 01 '22 at 13:35

1 Answers1

1

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.

Stefan
  • 17,448
  • 11
  • 60
  • 79
  • Unfortunately this only works on a local machine, since I got the IP address MachineName would just return the name of the local machine, because MachineName cannot take a IP adress as a parameter – Novellist Sep 01 '22 at 13:58
  • Can you explain what you want in one sentence? – Stefan Sep 01 '22 at 14:50
  • I want to get the name of the server, which I named "Server" (the PC that is my server) and not the name i have given the PC in the router, which is MeinServer: longh sentence short, I want it to return "server" and not "MeinServer.speedport.ip" – Novellist Sep 02 '22 at 11:42
  • From which machine? – Stefan Sep 02 '22 at 12:19
  • As I said... I have my computer which runs the command, getting the IP (192.168.2.109 - the server), I want the name of the server not the name in the router -- server-name is SERVER, router-dns-name is MEINSERVER(.speedport.ip) I want the SERVER name – Novellist Sep 02 '22 at 14:57