Assign static IP and set host name

Im trying to assign a static IP to my ESP32 and also set the host name.
I am able to get one or the other to work, but not get them to work together.

#include <WiFi.h>
void setup() {

IPAddress local_IP(192, 168, 1, 100);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(208, 67, 222, 222);
IPAddress secondaryDNS(208, 67, 220, 220);

WiFi.mode(WIFI_STA);
WiFi.hostname("ESP");
WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
WiFi.begin("xxxx", "yyyy");

while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}

question in a question:
The WiFi.config that that gives me a static IP is in the format local_IP, gateway, subnet, primaryDNS, secondaryDNS but the documentation for WiFi.config (and also looking at the library WiFi.h code) is ip, dns, gateway, subnet.

and according to the documentation this should also work, but doesn't WiFi.config (ip)

Hello, do yourself a favour and please read How to get the best out of this forum and modify your post accordingly (add code tags).

--

I never tried, I usually configure the IP address for my ESP directly in the DHCP side of the router

have you tried the other way around (hostname after config)

#include <WiFi.h>

IPAddress local_IP(192, 168, 1, 100);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(208, 67, 222, 222);
IPAddress secondaryDNS(208, 67, 220, 220);

const char* ssid = "xxx";
const char* password = "xxx";
const char* hostname = "ESP32";

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
  WiFi.hostname(hostname);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("WiFi Failed!");
    while(true) yield();
  }
  Serial.print("IP Address: "); Serial.println(WiFi.localIP());
}

void loop() {}

Thanks for your reply. I previously tried swapping that. I also tried your code.
No dice.
Both ways it doesn't show as a connected device in the router, but I can ping it at 1.100 and network scanner shows it at 1.100 host name shows on scanner as N/A

(Sorry about not tagging my code)

I have tried both and finished up setting a static IP in my router and could never get the hostname to change from the default espressif.

I'll give it another try

yep, saw & tried both of those. I can get either one to work by itself, but not together!

some routers have a tough time picking up the names, sometimes you need to reboot the box for the "new" (if device was seen before) name to be taken into account...

Tried 2 different brand routers (and reboots), same issue.
Also network scanner reports same info as routers.

I checked with this code; the program works and uses the assigned IP address - even though my router is configured to assign it a different one.

  • but the hostname is not working
/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com  
*********/

// Load Wi-Fi library
#include <WiFi.h>

// Replace with your network credentials (STATION)
const char* ssid = "my ssid";  // Enter SSID here
const char* password = "my pwd";  //Enter Password here

String hostname = "ESP32 Fixed IP";


// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output26State = "off";
String output27State = "off";

// Assign output variables to GPIO pins //*** changed to suit pins I'm using
const int output26 = 32;
const int output27 = 33;

// Set your Static IP address
IPAddress local_IP(192, 168, 1, 184);
// Set your Gateway IP address
IPAddress gateway(192, 168, 1, 1);

IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8);   //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output26, OUTPUT);
  pinMode(output27, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output26, LOW);
  digitalWrite(output27, LOW);
   
  WiFi.mode(WIFI_STA);
  WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
  WiFi.setHostname(hostname.c_str()); //define hostname

  // Configures static IP address
  if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("STA Failed to configure");
  }
  
  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /26/on") >= 0) {
              Serial.println("GPIO 26 on");
              output26State = "on";
              digitalWrite(output26, HIGH);
            } else if (header.indexOf("GET /26/off") >= 0) {
              Serial.println("GPIO 26 off");
              output26State = "off";
              digitalWrite(output26, LOW);
            } else if (header.indexOf("GET /27/on") >= 0) {
              Serial.println("GPIO 27 on");
              output27State = "on";
              digitalWrite(output27, HIGH);
            } else if (header.indexOf("GET /27/off") >= 0) {
              Serial.println("GPIO 27 off");
              output27State = "off";
              digitalWrite(output27, LOW);
            }
            
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #555555;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP32 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 26  
            client.println("<p>GPIO 26 - State " + output26State + "</p>");
            // If the output26State is off, it displays the ON button       
            if (output26State=="off") {
              client.println("<p><a href=\"/26/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/26/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 27  
            client.println("<p>GPIO 27 - State " + output27State + "</p>");
            // If the output27State is off, it displays the ON button       
            if (output27State=="off") {
              client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/27/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

And this code uses the IP address I fixed in the router and DOES set the hostname - although

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-set-custom-hostname-arduino/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>

// Replace with your network credentials (STATION)
const char* ssid = "what it is";  // Enter SSID here
const char* password = "and this";  //Enter Password here

String hostname = "ESP32 set wifi hostname";

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
  WiFi.setHostname(hostname.c_str()); //define hostname
  //wifi_station_set_hostname( hostname.c_str() );
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.print("RRSI: ");
  Serial.println(WiFi.RSSI());
  Serial.println(WiFi.getHostname());
}

void loop() {
  // put your main code here, to run repeatedly:
}

Connecting to WiFi .......192.168.1.28
RRSI: -44
ESP32 set wifi hostname

And the router shows ..

I’ll give it a try later today to see what I get on my network

Assigning the IP from DHCP and using bonjour seems so more flexible to me that I’ve never explored static IPs

Hi Jackson - I'm an i-phobe!

I have a NODE set up as a network scanner & logger so I use fixed IP for most of my network.

I would not try and assign xxx.xxx.x.100 as an IP address to begin with, chances are your router has assigned that to some other device. Personally i don't use static IP's for the reason that it limits you in possible connections.

const char* password = "my pwd";

Please remember that a valid password consist of a minimum of 8 characters. Here in Station mode it doesn't matter so much, and i understand that you don't want to post the actual one, but 'password' is a valid solution.

x.x.1.100 is a free IP on my network. My DHCP pool is x.x.x.200-.240
Im not having a problem assigning that IP, just assigning it AND specifying a hostname at the same time.

Not having an issue connecting to WiFI
(my WiFI password is complex, but not posted)

I understand, i just wish people would be consistently putting them here consisting of 8 characters or more.

In that case, have you tried assigning a 'hostname' (i guess you mean mDNS lookup) afterwards. Personally i am not that familiar with the ESP32 core, but on an ESP8266 you can do it after you have connected.