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

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

    Here is how i solved it. i know if you have several physical interfaces this might not select the exact eth you want.

    private string FetchIP()
    {
        //Get all IP registered
        List IPList = new List();
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                IPList.Add(ip.ToString());
            }
        }
    
        //Find the first IP which is not only local
        foreach (string a in IPList)
        {
            Ping p = new Ping();
            string[] b = a.Split('.');
            string ip2 = b[0] + "." + b[1] + "." + b[2] + ".1";
            PingReply t = p.Send(ip2);
            p.Dispose();
            if (t.Status == IPStatus.Success && ip2 != a)
            {
                return a;
            }
        }
        return null;
    }
    

提交回复
热议问题