但是又不知道本機IP是多少該怎麼辦呢?
獲取本機所有IP位址:
private void GetIP()
{
string hostName = Dns.GetHostName(); //取得本機名稱
//取得所有IP,包含IPV4和IPV6
System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);
foreach (IPAddress ip in addressList)
{
Console.WriteLine(ip.ToString());
}
Console.ReadLine();
}
以上的IP包含所有網卡(虛擬網卡)的IPV4和IPV6的IP如果想要只取IPV4的位址,需加入以下條件,
獲取本機所有IPV4位址:
private void GetIP()
{
string hostName = Dns.GetHostName(); //取得本機名稱
//取得所有IP,包含IPV4和IPV6
System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName);
foreach (IPAddress ip in addressList)
{
//過濾IPV4的位址
if (ip.AddressFamily == AddressFamily.InterNetwork)
Console.Writeline(ip.ToString());
}
Console.ReadLine();
}
以上包含所有網卡(虛擬網卡)的IPV4若想過濾掉虛擬網卡位址的話,必需使用下列程式碼實現,
獲取本機IPV4,過濾虛擬網卡:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetLocalIP());
Console.WriteLine("-- -- The End -- --");
Console.ReadKey();
}
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
{
return "找不到本機IP";
}
}
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位址啦!
沒有留言:
張貼留言