首页 > 解决方案 > ESP8266,连接 AP 时,请求特定 IP 或可发现主机名?

问题描述

ESP8266 代码中是否有任何方法可以向路由器询问特定 IP?我的意思是,在下面的例子中(我从网上复制的),它得到“192.168.1.3”。“3”部分是自动分配的,下次可能会改变。我希望这个数字是一个特定的数字。我知道我可以修改路由器设置以添加静态 IP,但至少对于我的路由器而言,添加静态 IP 既慢又不方便。我可以交换 ESP8266 板并运行相同的代码。路由器是我的,仅供我使用,所以如果我需要更改路由器的某些设置来授予来自客户端的此类请求,我可以这样做。

如果没有这样的功能,我可以通过特定名称使 ESP8266 可被发现(同样,不在路由器设置中创建翻译条目,而是在 ESP 代码中)?例如,如果 ESP8266 运行 Web 服务器,我可以通过“http://myserver1”而不是“http://192.168.1.3”之类的方式访问 Web 服务器吗?

#include <ESP8266WiFi.h>        // Include the Wi-Fi library

const char* ssid     = "SSID";         // The SSID (name) of the Wi-Fi network you want to connect to
const char* password = "PASSWORD";     // The password of the Wi-Fi network

void setup() {
  Serial.begin(115200);         // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println('\n');
  
  WiFi.begin(ssid, password);             // Connect to the network
  Serial.print("Connecting to ");
  Serial.print(ssid); Serial.println(" ...");

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }

  Serial.println('\n');
  Serial.println("Connection established!");  
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());         // Send the IP address of the ESP8266 to the computer
}

标签: microcontrolleresp8266arduino-esp8266esp8266wifi

解决方案


几乎所有的路由器都有DHCP Server。您可以做的是DHCP Reservation为您ESP8266的 MAC 地址创建一个。

对于域名,您可以在本地 PC 中创建主机条目。像这样的东西,

192.168.1.3 myserver1

更新

我发现教程可以回答静态 IP 配置。

域名的解析是由您完成的,DNS Server.因为您没有公共IP或实际域,因此您IP不会被任何DNS Servers人解析。所以你可以做的是DHCP在你的路由器中创建一个主机条目(创建这个主机条目也在上面的教程中完成)或者在你的本地 PC 中创建一个主机条目。

注意:我目前没有NodeMCU模块。否则我可以自己试试这个。


推荐阅读