获取本机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: }