获取本机IP(考虑多块网卡、虚拟机等复杂情况)
生活随笔
收集整理的這篇文章主要介紹了
获取本机IP(考虑多块网卡、虚拟机等复杂情况)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
方法1:
基本思路:
通過查詢本機路由表,獲取訪問默認網關時使用的網卡IP地址。該方法在有網絡的情況下適應性較好,如果本身不連接到互聯網,則無法獲取。
代碼如下:
1: /// <summary> 2: /// 獲取當前使用的IP 3: /// </summary> 4: /// <returns></returns> 5: public static string GetLocalIP() 6: { 7: string result = RunApp("route", "print", true); 8: Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)"); 9: if (m.Success) 10: { 11: return m.Groups[2].Value; 12: } 13: else 14: { 15: try 16: { 17: System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient(); 18: c.Connect("www.baidu.com", 80); 19: string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString(); 20: c.Close(); 21: return ip; 22: } 23: catch (Exception) 24: { 25: return null; 26: } 27: } 28: } 29: ? 30: /// <summary> 31: /// 獲取本機主DNS 32: /// </summary> 33: /// <returns></returns> 34: public static string GetPrimaryDNS() 35: { 36: string result = RunApp("nslookup", "", true); 37: Match m = Regex.Match(result, @"\d+\.\d+\.\d+\.\d+"); 38: if (m.Success) 39: { 40: return m.Value; 41: } 42: else 43: { 44: return null; 45: } 46: } 47: ? 48: /// <summary> 49: /// 運行一個控制臺程序并返回其輸出參數。 50: /// </summary> 51: /// <param name="filename">程序名</param> 52: /// <param name="arguments">輸入參數</param> 53: /// <returns></returns> 54: public static string RunApp(string filename, string arguments, bool recordLog) 55: { 56: try 57: { 58: if (recordLog) 59: { 60: Trace.WriteLine(filename + " " + arguments); 61: } 62: Process proc = new Process(); 63: proc.StartInfo.FileName = filename; 64: proc.StartInfo.CreateNoWindow = true; 65: proc.StartInfo.Arguments = arguments; 66: proc.StartInfo.RedirectStandardOutput = true; 67: proc.StartInfo.UseShellExecute = false; 68: proc.Start(); 69: ? 70: using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default)) 71: { 72: string txt = sr.ReadToEnd(); 73: sr.Close(); 74: if (recordLog) 75: { 76: Trace.WriteLine(txt); 77: } 78: if (!proc.HasExited) 79: { 80: proc.Kill(); 81: } 82: return txt; 83: } 84: } 85: catch (Exception ex) 86: { 87: Trace.WriteLine(ex); 88: return ex.Message; 89: } 90: }總結
以上是生活随笔為你收集整理的获取本机IP(考虑多块网卡、虚拟机等复杂情况)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Dreamweaver】前端初学者开发
- 下一篇: 源代码加密-防泄密解决方案-SDC沙盒