How to get the IP address of the server on which my C# application is running on?

前端 未结 26 2273
天命终不由人
天命终不由人 2020-11-22 06:01

I am running a server, and I want to display my own IP address.

What is the syntax for getting the computer\'s own (if possible, external) IP address?

Someon

26条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 06:43

    Get all IP addresses as strings using LINQ:

    using System.Linq;
    using System.Net.NetworkInformation;
    using System.Net.Sockets;
    ...
    string[] allIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
        .SelectMany(c=>c.GetIPProperties().UnicastAddresses
            .Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork)
            .Select(d=>d.Address.ToString())
        ).ToArray();
    

    TO FILTER OUT PRIVATE ONES...

    First, define an extension method IsPrivate():

    public static class IPAddressExtensions
    {
        // Collection of private CIDRs (IpAddress/Mask) 
        private static Tuple[] _privateCidrs = new []{"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"}
            .Select(c=>Tuple.Create(BitConverter.ToInt32(IPAddress
                                        .Parse(c.Split('/')[0]).GetAddressBytes(), 0)
                                  , IPAddress.HostToNetworkOrder(-1 << (32-int.Parse(c.Split('/')[1])))))
            .ToArray();
        public static bool IsPrivate(this IPAddress ipAddress)
        {
            int ip = BitConverter.ToInt32(ipAddress.GetAddressBytes(), 0);
            return _privateCidrs.Any(cidr=>(ip & cidr.Item2)==(cidr.Item1 & cidr.Item2));           
        }
    }
    

    ... And then use it to filter out private IPs:

    string[] publicIpAddresses = NetworkInterface.GetAllNetworkInterfaces()
        .SelectMany(c=>c.GetIPProperties().UnicastAddresses
            .Where(d=>d.Address.AddressFamily == AddressFamily.InterNetwork
                && !d.Address.IsPrivate() // Filter out private ones
            )
            .Select(d=>d.Address.ToString())
        ).ToArray();
    

提交回复
热议问题