c# - 试图从 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));
}
有什么可能有帮助的吗?谢谢。
解决方案
问题是您在其中设置的那个 URL 它返回下一个"192.168.1.1\n"
,因为您看到最后有一个\n
,这会导致您的问题,如果您添加.Replace("\n","")
它可以正常工作。
return System.Net.IPAddress.Parse(new System.Net.WebClient().DownloadString(serviceUrl).Replace("\n", ""));
推荐阅读
- bots - 在 Discord 中更改 Bot 角色的位置
- excel - 使用 VBA 从 Excel 文件目录中删除已知密码
- c# - 没有参数给出对应于 'form1.Form1(string[]) 的所需形式参数 'args'
- visual-studio-code - 在 vs 代码中安装 python 模块不起作用
- android -
在 Android Studio 4.0.2 - python-3.x - Python:Base64 解码编解码器无法解码位置 47-48 中的字节:无效的继续字节
- javascript - 反应 setTimeout - 内存泄漏
- c# - 如何中断从 c# interop 调用的 c++ 代码
- python - 求嵌套循环的时间复杂度
- python-3.x - python中的zip功能表现得很奇怪