如果要获取本机的IP地址,最简单的方法就是在命令提示符下面使用 “ipconfig” 命令。在C# 中,我们可以使用启动新 ipconfig 进程,然后读取输出的方法来实现。
public static string ipConfig() { Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = "ipconfig.exe"; p.Start(); p.WaitForExit(); string output = p.StandardOutput.ReadToEnd(); return output; }
如果我们只需要 IP 地址本身,使用 ifconfig 就不太方便了,这时候我们可以用 System.Net 中的 IPHostEntry 来获取本地 IP 地址。
public string GetLocalIP() { IPHostEntry host; string localIP = "< Not available, please check your network seetings! >"; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { localIP = ip.ToString(); break; } } return localIP; }
参考资料
StackOverFlow, http://stackoverflow.com/questions/6803073/get-local-ip-address-c-sharp
[Last Cited: 31-12-2014]
评论