using System;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Net.NetworkInformation
//获取本机ip地址
public static string GetLocalIPv4(NetworkInterfaceType _type)
{
string output = "";
foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
{
// 网络类型是所规定的并且网络再运行状态
if (item.NetworkInterfaceType == _type && item.OperationalStatus == OperationalStatus.Up)
{
foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
{
output = ip.Address.ToString();
}
}
}
}
return output;
}
public static string IPV4()
{
string ipv4 = GetLocalIPv4(NetworkInterfaceType.Wireless80211);
// 如果不是无线网卡,则获取有线网卡的地址
if (ipv4 == "")
{
ipv4 = GetLocalIPv4(NetworkInterfaceType.Ethernet);
// 如果有线网卡也没有获取到数据,则使用最开始可能包含虚拟网卡的方法来获取IP
if (ipv4 == "")
{
ipv4 = GetLocalIPv4(NetworkInterfaceType.Ethernet3Megabit);
if (ipv4 == "") {
ipv4 = GetLocalIPv4(NetworkInterfaceType.FastEthernetFx);
if (ipv4 == "") {
ipv4 = GetLocalIPv4(NetworkInterfaceType.FastEthernetT);
if(ipv4 == ""){
ipv4 = GetLocalIPv4(NetworkInterfaceType.Fddi);
if(ipv4 == ""){
ipv4 = GetLocalIPv4(NetworkInterfaceType.GigabitEthernet);
if(ipv4 == ""){
ipv4 = GetLocalIPv4(NetworkInterfaceType.Isdn);
if(ipv4 == ""){
ipv4 = GetLocalIPv4(NetworkInterfaceType.IPOverAtm);
}
}
}
}
}
}
}
}
return ipv4;
}
C#获取本机ip地址
最新推荐文章于 2024-01-16 09:51:46 发布