C# 正在尝试从C获取公共IP#
我正在尝试获取用户的公共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
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;
}