C# 获取本机IP_考虑多网卡的情况
2014-07-31 19:02
309 查看
转自:<a target=_blank href="http://blog.csdn.net/frombegintoend/article/details/9228759">http://blog.csdn.net/frombegintoend/article/details/9228759</a>
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Diagnostics;using System.Text.RegularExpressions;namespace _09获取本机IP_考虑多网卡_{class Program{static void Main(string[] args){Console.WriteLine(GetLocalIP());Console.ReadKey();}/// <summary>/// 获取当前使用的IP/// </summary>/// <returns></returns>public static string GetLocalIP(){string result = RunApp("route", "print", true);Match m = Regex.Match(result, @"0.0.0.0\s+0.0.0.0\s+(\d+.\d+.\d+.\d+)\s+(\d+.\d+.\d+.\d+)");if (m.Success){return m.Groups[2].Value;}else{try{System.Net.Sockets.TcpClient c = new System.Net.Sockets.TcpClient();c.Connect("www.baidu.com", 80);string ip = ((System.Net.IPEndPoint)c.Client.LocalEndPoint).Address.ToString();c.Close();return ip;}catch (Exception){return null;}}}/// <summary>/// 运行一个控制台程序并返回其输出参数。/// </summary>/// <param name="filename">程序名</param>/// <param name="arguments">输入参数</param>/// <returns></returns>public static string RunApp(string filename, string arguments, bool recordLog){try{if (recordLog){Trace.WriteLine(filename + " " + arguments);}Process proc = new Process();proc.StartInfo.FileName = filename;proc.StartInfo.CreateNoWindow = true;proc.StartInfo.Arguments = arguments;proc.StartInfo.RedirectStandardOutput = true;proc.StartInfo.UseShellExecute = false;proc.Start();using (System.IO.StreamReader sr = new System.IO.StreamReader(proc.StandardOutput.BaseStream, Encoding.Default)){string txt = sr.ReadToEnd();sr.Close();if (recordLog){Trace.WriteLine(txt);}if (!proc.HasExited){proc.Kill();}return txt;}}catch (Exception ex){Trace.WriteLine(ex);return ex.Message;}}}}
相关文章推荐
- 获取本机IP(考虑多块网卡、虚拟机等复杂情况)
- 获取本机IP_考虑多网卡的情况
- 获取本机IP_考虑多网卡的情况
- 获取本机IP(考虑多块网卡、虚拟机等复杂情况)
- c#获取和设置网卡ip/dns等信息
- c# 获取所有网卡的信息(IP。MAC)
- c#获取网卡的ip等信息
- C#中获取服务器IP,客户端IP以及网卡物理地址
- 获取本地 ip (多网卡的情况下)
- C#获取本地计算机名,IP,MAC(物理)地址
- 用C#编写获取远程IP,MAC的方法
- 使用C#调用外部Ping命令获取网络连接情况
- 使用C#调用外部Ping命令获取网络连接情况
- ASP.NET获取IP与MAC[using C#]
- C#中获取CPU序列号、网卡Mac地址、IP地址、硬盘序列号、登录用户名、PC类型、计算机名称、物理内存,Singleton模式
- 使用C#调用外部Ping命令获取网络连接情况