首页 > 解决方案 > 试图从 C# 获取公共 IP

问题描述

我正在尝试获取用户的公共 IP,但出现此错误:

    System.Net.IPAddress.InternalParse(string, bool)
    System.Net.IPAddress.Parse(string)
    Test.Form1.GetPublicIp(string) in Form1.cs
    Test.Form1.button2_Click(object, System.EventArgs) in Form1.cs
    System.Windows.Forms.Control.OnClick(System.EventArgs)
    System.Windows.Forms.Button.OnClick(System.EventArgs)
    System.Windows.Forms.Button.OnMouseUp(System.Windows.Forms.MouseEventArgs)
    System.Windows.Forms.Control.WmMouseUp(ref System.Windows.Forms.Message, System.Windows.Forms.MouseButtons, int)
    System.Windows.Forms.Control.WndProc(ref System.Windows.Forms.Message)
    System.Windows.Forms.ButtonBase.WndProc(ref System.Windows.Forms.Message)
    ...

我使用这段代码:

static System.Net.IPAddress GetPublicIp(string serviceUrl = "https://wtfismyip.com/text")
        {
            return System.Net.IPAddress.Parse(new System.Net.WebClient().DownloadString(serviceUrl));
        }

有什么可能有帮助的吗?谢谢。

标签: c#parsingip

解决方案


问题是您在其中设置的那个 URL 它返回下一个"192.168.1.1\n",因为您看到最后有一个\n,这会导致您的问题,如果您添加.Replace("\n","")它可以正常工作。

return System.Net.IPAddress.Parse(new System.Net.WebClient().DownloadString(serviceUrl).Replace("\n", ""));

推荐阅读