How to get an IP address in C #?

Suppose a computer is connected to many networks (actually more than one).

I can get a list of IP addresses that includes all the IP addresses that the computer has on the network, but how do I know if the IP address belongs to which network?

+4
source share
1 answer

Firstly, there are some terms that you need to know. These sample numbers assume an IPv4 network.

  • IP Address (192.168.1.1)
  • Subnet Mask (255.255.255.0)
  • network address (192.168.1.0)
  • network interface card, network adapter (there can be several of these on one hardware card)

To find out which network the IP address belongs to, you need to calculate the network address. This is easy if you take your IP address (either as a byte [4], or in UInt64), and bitwise "and" it using a subnet mask.

using System; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; namespace ConsoleApplication { public static class ConsoleApp { public static void Main() { var nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (var nic in nics) { var ipProps = nic.GetIPProperties(); // We're only interested in IPv4 addresses for this example. var ipv4Addrs = ipProps.UnicastAddresses .Where(addr => addr.Address.AddressFamily == AddressFamily.InterNetwork); foreach (var addr in ipv4Addrs) { var network = CalculateNetwork(addr); if (network != null) Console.WriteLine("Addr: {0} Mask: {1} Network: {2}", addr.Address, addr.IPv4Mask, network); } } } private static IPAddress CalculateNetwork(UnicastIPAddressInformation addr) { // The mask will be null in some scenarios, like a dhcp address 169.254.xx if (addr.IPv4Mask == null) return null; var ip = addr.Address.GetAddressBytes(); var mask = addr.IPv4Mask.GetAddressBytes(); var result = new Byte[4]; for (int i = 0; i < 4; ++i) { result[i] = (Byte)(ip[i] & mask[i]); } return new IPAddress(result); } } } 

Note that you can have multiple IP addresses on the same network that the VPN can have a submask of 255.255.255.255 (so that network address == IP address), etc.

+4
source

Source: https://habr.com/ru/post/1333658/


All Articles