1.常用的获取本机IP地址的方法如下:
try { string hostName = Dns.GetHostName(); IPHostEntry iPHostEntry = Dns.GetHostEntry(hostName); var addressV = iPHostEntry.AddressList.FirstOrDefault(q => q.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);//ip4地址 if (addressV != null) return addressV.ToString(); return "127.0.0.1"; } catch (Exception ex) { return "127.0.0.1"; }
但是以上获取IP地址的方法,可能获取不到你想要的IP地址,比如,你本机开启了虚拟机,VPN等,都会增加IP地址
2.以下通过Socket,连接UDP套接字并读取其本地终结点,可以拿到更精确的本机IP地址:
string localIP; 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(); }
在UDP套接字上连接具有以下效果:它设置发送/接收的目的地,丢弃来自其他地址的所有数据包。参照https://stackoverflow.com/questions/6803073/get-local-ip-address