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

前端 未结 26 1951
天命终不由人
天命终不由人 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<int, int>[] _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();
    
    0 讨论(0)
  • 2020-11-22 06:43

    To get the remote ip address the quickest way possible. You must have to use a downloader, or create a server on your computer.

    The downsides to using this simple code: (which is recommended) is that it will take 3-5 seconds to get your Remote IP Address because the WebClient when initialized always takes 3-5 seconds to check for your proxy settings.

     public static string GetIP()
     {
                string externalIP = "";
                externalIP = new WebClient().DownloadString("http://checkip.dyndns.org/");
                externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                               .Matches(externalIP)[0].ToString();
                return externalIP;
     }
    

    Here is how I fixed it.. (first time still takes 3-5 seconds) but after that it will always get your Remote IP Address in 0-2 seconds depending on your connection.

    public static WebClient webclient = new WebClient();
    public static string GetIP()
    {
        string externalIP = "";
        externalIP = webclient.DownloadString("http://checkip.dyndns.org/");
        externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                       .Matches(externalIP)[0].ToString();
        return externalIP;
    }
    
    0 讨论(0)
  • 2020-11-22 06:47

    Cleaner and an all in one solution :D

    //This returns the first IP4 address or null
    return Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
    
    0 讨论(0)
  • 2020-11-22 06:47

    I just thought that I would add my own, one-liner (even though there are many other useful answers already).


    string ipAddress = new WebClient().DownloadString("http://icanhazip.com");

    0 讨论(0)
  • using System;
    using System.Net;
    
    namespace IPADDRESS
    {
        class Program
        {
            static void Main(string[] args)
            {
                String strHostName = string.Empty;
                if (args.Length == 0)
                {                
                    /* First get the host name of local machine.*/
                    strHostName = Dns.GetHostName();
                    Console.WriteLine("Local Machine's Host Name: " + strHostName);
                }
                else
                {
                    strHostName = args[0];
                }
                /* Then using host name, get the IP address list..*/
                IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
                IPAddress[] addr = ipEntry.AddressList;
                for (int i = 0; i < addr.Length; i++)
                {
                    Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
                }
                Console.ReadLine();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:48

    The LINQ solution:

    Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""
    
    0 讨论(0)
提交回复
热议问题