我正在运行服务器,而且想显示本身的IP地址。 服务器
获取计算机本身(若是可能,外部)IP地址的语法是什么? ide
有人编写了如下代码。 测试
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
可是,我一般不信任做者,而且我不理解此代码。 有更好的方法吗? spa
#1楼
这是为了在VB.NET中以csv格式获取全部本地IP code
Imports System.Net
Imports System.Net.Sockets
Function GetIPAddress() As String
Dim ipList As List(Of String) = New List(Of String)
Dim host As IPHostEntry
Dim localIP As String = "?"
host = Dns.GetHostEntry(Dns.GetHostName())
For Each ip As IPAddress In host.AddressList
If ip.AddressFamily = AddressFamily.InterNetwork Then
localIP = ip.ToString()
ipList.Add(localIP)
End If
Next
Dim ret As String = String.Join(",", ipList.ToArray)
Return ret
End Function
#2楼
不,那几乎是最好的方法。 因为一台机器可能有多个IP地址,所以您须要迭代它们的集合以找到合适的IP地址。 ip
编辑:我惟一要更改的就是更改此: get
if (ip.AddressFamily.ToString() == "InterNetwork")
对此: string
if (ip.AddressFamily == AddressFamily.InterNetwork)
无需ToString枚举进行比较。 it
#3楼
namespace NKUtilities
{
using System;
using System.Net;
using System.Net.Sockets;
public class DNSUtility
{
public static int Main(string [] args)
{
string strHostName = "";
try {
if(args.Length == 0)
{
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine ("Local Machine's Host Name: " + strHostName);
}
else
{
// Otherwise, get the IP address of the host provided on the command line.
strHostName = args[0];
}
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for(int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
return 0;
}
catch(SocketException se)
{
Console.WriteLine("{0} ({1})", se.Message, strHostName);
return -1;
}
catch(Exception ex)
{
Console.WriteLine("Error: {0}.", ex.Message);
return -1;
}
}
}
}
在这里查看详细信息。 io
您必须记住您的计算机能够具备多个IP(实际上它老是具备)-所以,您追求的是哪一个IP。
#4楼
using System.Net;
string host = Dns.GetHostName();
IPHostEntry ip = Dns.GetHostEntry(host);
Console.WriteLine(ip.AddressList[0].ToString());
刚刚在个人机器上测试了它,就能够了。
#5楼
namespace NKUtilities
{
using System;
using System.Net;
public class DNSUtility
{
public static int Main (string [] args)
{
String strHostName = new String ("");
if (args.Length == 0)
{
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName ();
Console.WriteLine ("Local Machine's Host Name: " + strHostName);
}
else
{
strHostName = args[0];
}
// Then using host name, get the IP address list..
IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString ());
}
return 0;
}
}
}