需要using System.Net.NetworkInformation;
原理就是獲取網卡的信息。
//下面這段代碼是我在百度貼吧找來的,經檢驗是正確的
string userIp = "";
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); ;
foreach (NetworkInterface adapter in adapters)
{
if (adapter.Supports(NetworkInterfaceComponent.IPv4))
{
UnicastIPAddressInformationCollection uniCast = adapter.GetIPProperties().UnicastAddresses;
if (uniCast.Count > 0)
{
foreach (UnicastIPAddressInformation uni in uniCast)
{
//得到IPv4的地址。 AddressFamily.InterNetwork指的是IPv4
if (uni.Address.AddressFamily == AddressFamily.InterNetwork)
{
userIp =uni.Address.ToString();
}
}
}
}
}

