打印
[Wi-Fi/蓝牙/Zigbee…]

在Arduino获取公网IP的方法

[复制链接]
200|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
gaoyang9992006|  楼主 | 2025-6-12 08:52 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

最开始 我使用的是http://api.ipify.org 提供 的API接口,
因为是http访问,实现非常容易。最近发现这个接口无法访问了,可能官方停止这个接口了。
void getPublicIP() 
{
  http.begin(client, "http://api.ipify.org");
  Serial.print("[HTTP] GET...\n");
  int httpCode = http.GET();

  if (httpCode > 0) {
    // HTTP header has been send and Server response header has been handled
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);

    // file found at server
    if (httpCode == HTTP_CODE_OK)
    {
      publicIP = http.getString();
      Serial.print("Your public IP address is: ");
      Serial.println(publicIP);
      
      // Optionally, use this IP address for further processing
      // For example, you can use this IP with a geolocation API to get your city name
    }
  }
  else
  {
    Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
  }
  http.end();
}
然后我又找到了一个新的本地网络的外网IP获取网址 https://iplark.com/ipapi/public/ip
这个地址是https开头的,直接替换无法访问的。
修改如下,解决了访问https问题,我自己做的网络天气日历又可以自动获取地理位置信息了。
void getPublicIP() 
{
  WiFiClientSecure client_s;
  // 跳过证书验证(仅用于测试,生产环境建议配置根证书)
  client_s.setInsecure();

  // 发起HTTPS请求
  if (http.begin(client_s, "https://iplark.com/ipapi/public/ip"))
  {
    Serial.print("[HTTP] GET...\n");
    int httpCode = http.GET();

    if (httpCode > 0)
    {
      Serial.printf("[HTTP] GET... code: %d\n", httpCode);
      if (httpCode == HTTP_CODE_OK) {
        publicIP = http.getString();
        Serial.print("Your public IP address is: ");
        Serial.println(publicIP);
      }
    } else
    {
      Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }
    http.end();
  } else
  {
    Serial.println("[HTTP] Unable to connect");
  }
}








使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:如果你觉得我的分享或者答复还可以,请给我点赞,谢谢。

2023

主题

16265

帖子

218

粉丝