Search code examples
microcontrolleresp8266arduino-esp8266esp8266wifi

ESP8266, when connecting to AP, requesting sepcific IP or discoverable host name?


Is there any way in the ESP8266 code to ask the router for a specific IP? I mean, in the following example (which I copied from the web), it gets "192.168.1.3". The part "3" is automatically assigned, and may change next time. I want this number to be a specific number. I know I can modify the router setting to add a static IP, but at least for my router, adding a static IP is slow and inconvenient. And I may swap the ESP8266 board and run the same code. The router is mine, and used only by me, so if I need to change some settings of the router to grant this kind of request from the client, I can do that.

If there is no such feature, can I make the ESP8266 discoverable by a specific name (again, without creating a translation entry in the router settings, but within the ESP code)? For example, if the ESP8266 runs a web server, can I make the web server accessible by something like "http://myserver1" instead of "http://192.168.1.3"?

#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
}

Solution

  • Almost all routers have DHCP Server. What you can do is create a DHCP Reservation for your ESP8266s MAC Address.

    For domain name what you can do is crate host entry in your local PC. Something like this,

    192.168.1.3 myserver1
    

    Update

    I have found this tutorial which can answer to static IP configuration.

    The resolution of the domain name is done by the DNS Server. Since you don't have a public IP or actual domain, your IP will not resolved by any DNS Servers out there. So what you can do is crate a DHCP host entry in your router (creating this host entry is also done in above tutorial) or create a host entry inside your local PC.

    Note: I currently don't have a NodeMCU module. Otherwise I could have try this myself.