There are many ways to get the local IP address online. There are some commonly used first-line products:
Enumerate local network cards
using ; using ; foreach (NetworkInterface netif in () .Where(a => ) .Where(a => == ) .Where(a => != ) .Where(a => ().GetIPv4Properties() != null) .Where(a => ().(ua => == )) .Where(a => ().(ua => )) ) { ("Network Interface: {0}", ); IPInterfaceProperties properties = (); foreach (IPAddressInformation unicast in ) ("\tUniCast: {0}", ); }
The information obtained is relatively comprehensive, which is equivalent to the information of the network card, but it cannot distinguish between virtual network card (such as docker).
Try to connect to an IP address
string localIP; using (Socket socket = new Socket(, , 0)) { ("8.8.8.8", 65530); IPEndPoint endPoint = as IPEndPoint; localIP = (); } (localIP);
A virtual network card can be avoided, but it may not be applicable to intranet addresses. At the same time, the network must be online and other servers can be connected.
Borrow DNS resolution
using ; string sHostName = (); IPHostEntry ipE = (sHostName); IPAddress[] IpA = ; for (int i = 0; i < ; i++) { ("IP Address {0}: {1} ", i, IpA[i].ToString()); }
IPAddress can also continue to make more precise selections by filtering IPv4 methods, which is similar to the first method. The operation method is very concise, but just like obtaining network card information, it is impossible to distinguish between virtual network card.
Summarize
For cases where there are dual network cards, often both network cards are valid IPV4 addresses. At this time, you need to use Method 2 to distinguish them through local area network or wide area network access. Of course, you can also choose a more complex method: use the broadcast service on the LAN, and then capture the packet to determine the obtained network address.
The above is the detailed content of three ways to obtain a local IP address in C#. For more information about obtaining a local IP address in C#, please follow my other related articles!