Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 正在尝试从C获取公共IP#_C#_Parsing_Ip - Fatal编程技术网

C# 正在尝试从C获取公共IP#

C# 正在尝试从C获取公共IP#,c#,parsing,ip,C#,Parsing,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.F

我正在尝试获取用户的公共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));
        }
有什么可以帮忙的吗?
谢谢。

问题是,您在其中设置的URL返回下一个
“192.168.1.1\n”
,因为您看到末尾有一个
\n
,这会导致您的问题,如果您添加
。替换(“\n”,”)
,它工作正常

return System.Net.IPAddress.Parse(new System.Net.WebClient().DownloadString(serviceUrl).Replace("\n", ""));
静态字符串GetIPAddress()
{  
字符串地址=”;
WebRequest=WebRequest.Create(“http://checkip.dyndns.org/");  
使用(WebResponse=request.GetResponse())
使用(StreamReader stream=newstreamreader(response.GetResponseStream()))
{  
地址=stream.readToEnter代码hered();
}  
int first=address.IndexOf(“地址:”)+9;
int last=address.LastIndexOf(“”);
地址=地址.子字符串(第一,最后-第一);
回信地址;
} 

查看更多详细信息

使用
DownloadString(serviceUrl).Trim()
还有,为什么我被否决了?:(
static string GetIPAddress()  
{  
    String address = "";  
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");  
    using (WebResponse response = request.GetResponse())  
    using (StreamReader stream = new StreamReader(response.GetResponseStream()))  
     {  
        address = stream.ReadToEnenter code hered();  
     }  
     int first = address.IndexOf("Address: ") + 9;  
     int last = address.LastIndexOf("</body>");  
     address = address.Substring(first, last - first);  
     return address;  
}