【问题标题】:Can't get public IP address from ESP8266 using ipify无法使用 ipify 从 ESP8266 获取公共 IP 地址
【发布时间】:2018-10-29 02:44:37
【问题描述】:

我正在使用 NodeMCU 来使用 ESP8266,我想使用 ipify 来获取公共 IP 地址。 但我在httpCode 上得到-1。这是为什么呢?

如果我输入api.ipify.org,它会正确获取我的公共 IP 地址。

void loop() {
  Serial.println(WiFi.status());
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
    Serial.println("az");
    HTTPClient http;  //Declare an object of class HTTPClient
    http.begin("https://api.ipify.org/?format=json");  //Specify request destination
    int httpCode = http.GET();                                                                  //Send the request
    Serial.println(httpCode);  //<<---- Here I get -1
    if (httpCode > 0) { //Check the returning code
      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);                     //Print the response payload
    }
    http.end();   //Close connection
  }
  delay(10000);    //Send a request every 30 seconds
}

【问题讨论】:

    标签: arduino ip-address esp8266 arduino-esp8266


    【解决方案1】:
    http.begin("https://api.ipify.org/?format=json");  
    

    您正在使用 HTTPClient 浏览 HTTPS 网站(HTTP + SSL/TLS 隧道),但您使用了错误的 .begin() 调用。 begin(String url 调用需要http:// URL,而不是https://。如果要使用HTTPS安全浏览网站,需要使用begin(String url, String httpsFingerprint)link)功能。您可以关注this guide,找到需要的httpsFingerprint。但是,使用 HTTPS 会导致大量的内存开销和处理时间。对于浏览“我的公共IP是什么”网站的情况,我建议您改为浏览http://版本,因为响应不是机密信息。

    所以,你可以这样做

    http.begin("http://api.ipify.org/?format=json");  
    

    【讨论】:

      【解决方案2】:

      你可以试试:

      String getIp()
      {
        WiFiClient client;
        if (client.connect("api.ipify.org", 80)) 
        {
            Serial.println("connected");
            client.println("GET / HTTP/1.0");
            client.println("Host: api.ipify.org");
            client.println();
        } else {
            Serial.println("Connection to ipify.org failed");
            return String();
        }
        delay(5000);
        String line;
        while(client.available())
        {
          line = client.readStringUntil('\n');
          Serial.println(line);
        }
        return line;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-16
        • 2016-12-15
        • 2017-09-23
        • 2018-10-22
        • 1970-01-01
        • 2021-12-22
        • 2014-12-16
        • 2020-12-10
        相关资源
        最近更新 更多