using System.Net.NetworkInformation; using System.Net.Sockets; namespace formula_manage.UserClass { public class get_local_ip_address { public static string getLocalIPAddressWithNetworkInterface(NetworkInterfaceType _type)//获取本机ip并以字符串方式返回 { 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 IP_Address() { string ip; ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Ethernet); if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Wireless80211); if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Ppp); if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Wwanpp); if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.TokenRing); if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Fddi); if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.GenericModem); if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.IPOverAtm); if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Tunnel); if (ip == "") ip = getLocalIPAddressWithNetworkInterface(NetworkInterfaceType.Unknown); if (ip == "") ip = "127.0.0.1"; return ip; } } }