How to get the IP address in C#?

我们两清 提交于 2019-11-30 22:33:53
sisve

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!