C# 获取本机IP地址
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Net.NetworkInformation; namespace Miracom.MESCore.Utils { /// <summary> /// 封装IP相关方法 /// 包含方法: /// + static List getIPAddressList() /// + static string getIPAddress() /// + static string getIPAddressBySocket() /// + static string getIPAddressByNetworkInterface(NetworkInterfaceType _type) /// /// </summary> /// <Author>CY</Author> public static class IPHelper { /// <summary> /// 获取本机所有的IP地址 /// </summary> /// <returns>IP字符串列表</returns> public static List<string> getIPAddressList() { List<string> ipList = new List<string>(); IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in ipEntry.AddressList) { ipList.Add("IP Address: " + ip.ToString()); } return ipList; } /// <summary> /// 获取本机IPv4地址 /// </summary> /// <returns>IPv4字符串</returns> public static string getIPAddress() { IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork)//如果需要获取ipv6地址,使用AddressFamily.InterNetworkV6 { return ip.ToString(); } } return null; } /// <summary> /// 通过使用UDP Socket连接来查看本机IP地址 /// 因为是获取网络连接中实际使用的IP,所以更准确 /// </summary> /// <returns>IPv4字符串</returns> public static string getIPAddressBySocket() { string localIP = string.Empty; using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) { socket.Connect("8.8.8.8", 65530); IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; localIP = endPoint.Address.ToString(); } return localIP; } /// <summary> /// 使用NetworkInterface查看 并返回指定类型的IP地址 /// </summary> /// <param name="_type">可选参数:IP的具体类型,默认为Ethernet类型</param> /// <returns>指定的IP字符串</returns> public static string getIPAddressByNetworkInterface(NetworkInterfaceType _type = NetworkInterfaceType.Ethernet) { 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) { return ip.Address.ToString(); } } } } return null; } } }