Get public/external IP address?

前端 未结 26 1962
鱼传尺愫
鱼传尺愫 2020-11-22 14:32

I cant seem to get or find information on finding my routers public IP? Is this because it cant be done this way and would have to get it from a website?

26条回答
  •  孤街浪徒
    2020-11-22 14:59

    With a few lines of code you can write your own Http Server for this.

    HttpListener listener = new HttpListener();
    listener.Prefixes.Add("http://+/PublicIP/");
    listener.Start();
    while (true)
    {
        HttpListenerContext context = listener.GetContext();
        string clientIP = context.Request.RemoteEndPoint.Address.ToString();
        using (Stream response = context.Response.OutputStream)
        using (StreamWriter writer = new StreamWriter(response))
            writer.Write(clientIP);
    
        context.Response.Close();
    }
    

    Then anytime you need to know your public ip, you can do this.

    WebClient client = new WebClient();
    string ip = client.DownloadString("http://serverIp/PublicIP");
    

提交回复
热议问题