vb.net 获取 IP 和计算机名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41486581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:09:29  来源:igfitidea点击:

Get the IP and Computer Name

vb.nethostname

提问by rchongo

I have this code:

我有这个代码:

localIp = Request.UserHostName
hostName = DetermineCompName(localIp)

Session.Add("localIp", localIp)
Session.Add("hostName", hostName)

As you can see, I put the 2 variables on a session so that I can use it when I want. Testing the app on 10 computers, I saw that on some of the computers it gets the Client IP and the Computer name, but on others it goes empty.

如您所见,我将 2 个变量放在一个会话中,以便我可以在需要时使用它。在 10 台计算机上测试该应用程序,我发现在某些计算机上它获取客户端 IP 和计算机名称,但在其他计算机上它变为空。

As in some computers it works, I don't understand what's wrong. Does anyone have the right method to do this?

就像在某些计算机中一样,它可以工作,我不明白出了什么问题。有没有人有正确的方法来做到这一点?

回答by Rem

To get the computer name you can simply do:

要获取计算机名称,您只需执行以下操作:

Dim hostName As String = Environment.MachineName 

or:

或者:

Dim hostName As String = My.Computer.Name

For the IP it's a little bit trickier, I assume you want the ipV4, so you can try this:

对于 IP,它有点棘手,我假设你想要 ipV4,所以你可以试试这个:

Dim localIp As String
For Each address As System.Net.IPAddress In System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList
    If address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
        localIp = address.ToString()
        Exit For
    End If
Next

Please note that if you do just:

请注意,如果您只是:

System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName).AddressList(0).ToString()

then this will return the ipV6.

那么这将返回ipV6。