You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取公网IP地址:离线状态下程序崩溃的修复需求

解决离线时程序崩溃的问题

嘿,这个问题太常见了——你的代码现在完全没处理网络异常,当离线或者请求失败时,WebRequest.GetResponse()会直接抛出未捕获的异常,导致程序崩溃。咱们只需要给代码加上异常捕获逻辑,就能让程序在离线时友好地显示"no connection"啦。

修改后的完整代码

private string getMyIPAddress() 
{
    string Address = "";
    try
    {
        WebRequest request = WebRequest.Create("http://checkip.dyndns.com");
        using (WebResponse response = request.GetResponse())
        using (StreamReader stream = new StreamReader(response.GetResponseStream()))
        {
            Address = stream.ReadToEnd();
            int first = Address.IndexOf("Address: ") + 9;
            int last = Address.IndexOf("</body>");
            Address = Address.Substring(first, last - first);
        }
    }
    catch (WebException ex)
    {
        // 可选:在这里记录异常信息,方便后续调试
        // Debug.WriteLine($"网络请求失败: {ex.Message}");
        Address = "no connection";
    }
    catch (Exception ex)
    {
        // 捕获其他可能的异常(比如HTML解析出错)
        // Debug.WriteLine($"其他错误: {ex.Message}");
        Address = "no connection";
    }
    textBox4.Text = Address;
    return Address;
}

关键修改点

  • 添加try-catch块:把所有网络请求和HTML解析的逻辑放到try块里,这样任何异常都会被捕获,不会直接导致程序崩溃
  • 针对性捕获WebException:这是网络请求失败时最常抛出的异常(比如离线、服务器不可达),捕获后直接设置提示文本
  • 通用异常兜底:额外捕获Exception,防止因为目标页面结构变化(比如"Address: "字符串消失)导致解析出错崩溃
  • 统一设置文本框:不管请求成功还是失败,最后都会把Address的值赋值给textBox4,确保界面始终有内容显示

这样修改后,离线时程序就会显示"no connection",而不是直接崩溃啦。

内容的提问来源于stack exchange,提问作者Jezhisaur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:07:27