我正在運行服務器,而且想顯示本身的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
這是爲了在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
不,那幾乎是最好的方法。 因爲一臺機器可能有多個IP地址,所以您須要迭代它們的集合以找到合適的IP地址。 ip
編輯:我惟一要更改的就是更改此: get
if (ip.AddressFamily.ToString() == "InterNetwork")
對此: string
if (ip.AddressFamily == AddressFamily.InterNetwork)
無需ToString
枚舉進行比較。 it
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。
using System.Net; string host = Dns.GetHostName(); IPHostEntry ip = Dns.GetHostEntry(host); Console.WriteLine(ip.AddressList[0].ToString());
剛剛在個人機器上測試了它,就能夠了。
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; } } }