简体   繁体   中英

How to get the IP address in C#?

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

I can get a list of IP addresses which includes all IP addresses the computer have in networks, but how can I know that an IP address belongs to which network?

First, there are some terms you need to know. These example numbers presume an IPv4 network.

  • IP address (192.168.1.1)
  • subnet mask (255.255.255.0)
  • network address (192.168.1.0)
  • network interface card, NIC (one hardware card may have several of these)

To see which network an IP address belongs to requires you to calculate the network address. This is easy if you take your IP address (either as an Byte[4] or an UInt64), and bitwise "and" it with your 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.x.x
            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 several IP addresses on the same network, that VPN connections may have a submask of 255.255.255.255 (so the network address == IP address), etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM