我正在寻找识别系统是否连接到网络或在系统上安装虚拟机时获取本地IP地址的方法。 这是返回本地IP地址的代码:
public static string LocalIPAddress()
{
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
}
但是当系统没有连接到网络时,它会返回另一个VM的ip地址
我也发现了这种方法
System.Net.NetworkInformation.NetworkInterface.isconnected
方法可用,但即使网络电缆已拔下,它也会返回true
有没有办法找出系统是否连接?
答案 0 :(得分:2)
试试这个:
using System.Net;
private string GetIP()
{
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
return addr[addr.Length-1].ToString();
}
答案 1 :(得分:1)
以下行将获取您的本地IP地址
string ipadress = Dns.GetHostEntry(Dns.GetHostName())
.AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork)
.ToString();
答案 2 :(得分:0)
答案 3 :(得分:0)
Try This:
using System;
using System.Net;
namespace GetLocalIP
{
class Program
{
static void Main(string[] args)
{
string host = Dns.GetHostName();
string AddressIP6 = string.Empty;
IPAddress[] IPAdd = Dns.GetHostAddresses(host);
foreach (IPAddress ip6 in IPAdd){
AddressIP6 = ip6.ToString();
}
Console.WriteLine("Local system IP Address : " + AddressIP6);
Console.ReadKey();
}
}
}