简体   繁体   English

你如何获得远程计算机的主机名?

[英]How do you get hostname of remote computer?

I'm currently developing a client-server desktop application on C# for my assignment.我目前正在 C# 上为我的任务开发客户端-服务器桌面应用程序。 I managed to retrieve the IP address of remote computer.我设法检索了远程计算机的 IP 地址。 Can I get the hostname of that remote computer by using IP Address?我可以使用 IP 地址获取该远程计算机的主机名吗?

Here is my code:这是我的代码:

    private static string GetMachineNameFromIPAddress(string ipAddress)
    {
        string machineName = string.Empty;
        try
        {
            IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress);

            machineName = hostEntry.HostName;

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString());
        }

        return machineName;
    }

I put the retrieved IP address into a label我将检索到的 IP 地址放入标签中

    var socketip = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
    ipLabel.Text = socketip;

but it's not appearing when I tried to display it with this code但是当我尝试使用此代码显示它时它没有出现

    string CompName = GetMachineNameFromIPAddress(socketip);
    listBox1.Items.Add("Computer Name: " + CompName);

Anyone know why?有谁知道为什么?

It's possible that DNS may not have a hostname associated with that IP address. DNS 可能没有与该 IP 地址关联的主机名。 If you have access, try running the command below on the client and force the update with DNS.如果您有访问权限,请尝试在客户端上运行以下命令并使用 DNS 强制更新。 Here's more info on how you would do it: Renew DNS client registration using the ipconfig command以下是有关如何执行此操作的更多信息: 使用 ipconfig 命令更新 DNS 客户端注册

ipconfig /registerdns ipconfig /注册DNS

Alternatively you could use Microsoft's ARP utility and just use the MAC address.或者,您可以使用 Microsoft 的 ARP 实用程序并仅使用 MAC 地址。 Here's an article that would help with that route: Resolve IP Address And Host Name From MAC Address using C# and Windows ARP Utility这是一篇有助于解决该路由的文章: Resolve IP Address And Host Name From MAC Address using C# and Windows ARP Utility

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM