获取本机IP_考虑多网卡的情况
生活随笔
收集整理的這篇文章主要介紹了
获取本机IP_考虑多网卡的情况
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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;}}}
}
轉載于:https://www.cnblogs.com/liqipeng/p/4576161.html
總結
以上是生活随笔為你收集整理的获取本机IP_考虑多网卡的情况的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 选择Asp for javascript
- 下一篇: 2013年06月电脑公司GHOSTXPS