且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取使用C#计算机名称

更新时间:2023-11-08 23:32:28

这未必是可行的。

您可以尝试扭转从IP地址查找名称,使用类似

 私人的String [] GetHostnamesForIpAddress(字符串ip地址)
{
   VAR HOSTIP = IPAddress.Parse(ip地址);
   IPHostEntry Hostinfo中= Dns.GetHostByAddress(主机IP);   返回hostInfo.Alias​​es;
}

在一个本地网络(其中客户端是本地的你,例如在企业网络中),这很可能是好的,只要所有客户端在DNS反向IP映射。

在互联网上,这是不太可能对大多数客户的工作。你只需要IP地址去了,一般这些不会有反向DNS映射设置。事实上,一个可怕的很多机器在那里将是代理服务器和网关的NAT后面,只有私人的,不可路由的IP地址,以便您不可能做一个反向查找。

I am using this code in cs file into an asp.net page for getting ip address from the logged user:

cmd.Parameters.AddWithValue("@ip",System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);

I would like to have also his computer name, as well. How do I do that?

This is not necessarily possible.

You can attempt to reverse lookup the name from the ip address, using something like

private string[] GetHostnamesForIpAddress(string ipAddress)
{
   var hostIp= IPAddress.Parse(ipAddress);
   IPHostEntry hostInfo = Dns.GetHostByAddress(hostIp);

   return hostInfo.Aliases;
}

On a local network (where your client is local to you, e.g. on a corporate network), this may well be ok, as long as all the clients have reverse ip mappings in DNS.

Over the internet, it is far less likely to work for most clients. You only have the IP address to go on, and generally these won't have reverse DNS mappings set up. In fact, an awful lot of machines out there will be behind proxies and NAT gateways and only have private, non-routable ip addresses, for which you can't possibly do a reverse lookup.