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

前端 未结 26 2264
天命终不由人
天命终不由人 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:49

    To find IP address list I have used this solution

    public static IEnumerable GetAddresses()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
    }
    

    But I personally like below solution to get local valid IP address

    public static IPAddress GetIPAddress(string hostName)
    {
        Ping ping = new Ping();
        var replay = ping.Send(hostName);
    
        if (replay.Status == IPStatus.Success)
        {
            return replay.Address;
        }
        return null;
     }
    
    public static void Main()
    {
        Console.WriteLine("Local IP Address: " + GetIPAddress(Dns.GetHostName()));
        Console.WriteLine("Google IP:" + GetIPAddress("google.com");
        Console.ReadLine();
    }
    

提交回复
热议问题