在Arduino获取公网IP的方法
最开始 我使用的是http://api.ipify.org 提供 的API接口,
因为是http访问,实现非常容易。最近发现这个接口无法访问了,可能官方停止这个接口了。
void getPublicIP()
{
http.begin(client, "http://api.ipify.org");
Serial.print(" GET...\n");
int httpCode = http.GET();
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf(" 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(" 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(" GET...\n");
int httpCode = http.GET();
if (httpCode > 0)
{
Serial.printf(" 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(" GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
} else
{
Serial.println(" Unable to connect");
}
}
在 Arduino 上获取公网 IP,可通过连接网络后访问公网 IP 查询接口(如icanhazip.com、ipify.org)。用 ESP8266/ESP32 等带 WiFi 功能的板卡,通过 HTTP 客户端发送请求,解析返回的文本数据即得公网 IP,需确保网络通畅并处理可能的请求超时。 这个思路很不错,是如何想到的呢。
页:
[1]