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

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

    The only way to know your public IP is to ask someone else to tell you; this code may help you:

    public string GetPublicIP()
    {
        String direction = "";
        WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
        using (WebResponse response = request.GetResponse())
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            direction = stream.ReadToEnd();
        }
    
        //Search for the ip in the html
        int first = direction.IndexOf("Address: ") + 9;
        int last = direction.LastIndexOf("");
        direction = direction.Substring(first, last - first);
    
        return direction;
    }
    

提交回复
热议问题