Skip to content

hostname can not set #806

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
llqy opened this issue Nov 3, 2017 · 29 comments
Closed

hostname can not set #806

llqy opened this issue Nov 3, 2017 · 29 comments

Comments

@llqy
Copy link

llqy commented Nov 3, 2017

Please fill the info fields, it helps to get you faster support ;)

If you have a Guru Meditation Error, please decode it:
https://github.com/me-no-dev/EspExceptionDecoder

----------------------------- Remove above -----------------------------

Hardware:

Board: ?ESP32 Dev Module?
Core Installation/update date: ?11/jul/2017?
IDE name: ?Arduino IDE? ?Platform.io? ?IDF component?
Flash Frequency: ?40Mhz?
Upload Speed: ?115200?

Description:

I can not set hostname use WiFi.setHostname("node1");

Sketch:

/*
 * main.cpp

 *
 *  Created on: 2017年11月3日
 *      Author: I am xxx
 */
#include <arduino.h>
#include <WiFi.h>
#include <PubSubClient.h>

const char* ssid = "PDCN_yalong";
const char* password =  "lala123456789";
const char* mqttServer = "192.168.100.217";
const int mqttPort = 1883;
const char* mqttUser = "yourMQTTuser";
const char* mqttPassword = "yourMQTTpassword";

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {

  Serial.begin(115200);
  WiFi.setHostname("node1");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

  client.setServer(mqttServer, mqttPort);

  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");

    if (client.connect("ESP32Client" )) {

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);

    }
  }

  client.publish("esp/test", "Hello from ESP32");

}

void loop() {

  client.publish("/home/lala", "3.33");
  client.loop();
  delay(5000);
  //Serial.available()
}



Debug Messages:

ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:812
load:0x40078000,len:0
load:0x40078000,len:10212
entry 0x40078a00
E (20) tcpip_adapter: tcpip_adapter is not initialized!
abort() was called at PC 0x40113f33 on core 1

Backtrace: 0x40087b30:0x3ffd56a0 0x40087c2f:0x3ffd56c0 0x40113f33:0x3ffd56e0 0x400d1f35:0x3ffd5720 0x400d138f:0x3ffd5740 0x4011afab:0x3ffd5760

Rebooting...
@llqy llqy closed this as completed Nov 4, 2017
@llqy llqy reopened this Nov 4, 2017
@llqy
Copy link
Author

llqy commented Nov 4, 2017

I change the order of Statement ,than it is worked.

  WiFi.begin(ssid, password);
  WiFi.setHostname("node1");

@doronby
Copy link

doronby commented Feb 10, 2019

I tried it both way on a DFrobot firebeetle esp32 board and it DOES not work for me.
when I ping -a IP_ADDRESS I get "espressif.lan." as node name.

Here is the test:

#include <WiFi.h>

void setup() {
// put your setup code here, to run once:

}

void loop() {
// put your main code here, to run repeatedly:
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.setHostname("My ESP32 Test Node");
WiFi.begin("MyAccessPoint", "MyPass"); //put real data here.
WiFi.setHostname("ESP TEST NODE");
while (WiFi.waitForConnectResult() != WL_CONNECTED)
{ Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(5000);
ESP.restart();
}

@lbernstone
Copy link
Contributor

hostname != dns . Your dhcp server is doing whatever you are seeing there in dns.
https://github.com/espressif/arduino-esp32/blob/master/libraries/ESPmDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino

@doronby
Copy link

doronby commented Feb 10, 2019

My google mesh router is providing the same name no matter what I do...:("espressif.lan.")
I have multiple ESP boards and I would like to give each a uniqe name of my choosing.
How do I change it to my specifications ?

@vcmorini
Copy link

vcmorini commented Jun 5, 2019

@doronby , any luck?

@HarmOtten
Copy link

I have the same issue.
When I don't set the hostname in the sketch, the DHCP server sees it as "espressive".
When I do WiFi.setHostname("abcd"); as first statement in my sketch, the hostname in the DHCP server shows empty.
Board: ESP32 DevKIT V1
IDE name: Arduino IDE v1.8.9

All my ESP8266 boards are able to set a hostname. Why isn't this possible with ESP32?

@minida28
Copy link

Should I open a new ticket for this...?
In AP mode, I changed the hostname using WiFi.softAPsetHostname("myname").
When I checked the hostname using WiFi.softAPgetHostname(), the result hostname is always espressif.

@HarmOtten
Copy link

I was hoping this issue could be re-opened...

@tom-oleson
Copy link

I hope this issue can be re-opened. It is NOT fixed for the ESP32 library. I've tried every combo I've seen discussed and none of them work. Always shows up blank on my WiFi router. Every other WiFi device I connect with shows up perfectly but not my ESP32.

Neither, WiFi.setHostname() nor WiFi.softAPsetHostname() work in any call location.

Arduino IDE 1.8.10
ESP32 Dev Module 1.0.4 (and tried 1.0.3)

@moelski
Copy link

moelski commented Dec 5, 2019

Hi !
Same here. No Hostname shows up in my router.
Using also 1.8.10 with 1.0.4 Lib.

@sparkescreative
Copy link

Same here.... using ESP32-CAM

@alve89
Copy link

alve89 commented Dec 10, 2019

+1

1 similar comment
@richard-scott
Copy link

+1

@HarmOtten
Copy link

@llqy Can you please reopen this issue?

@richard-scott
Copy link

richard-scott commented Dec 16, 2019

Ok, for my code, I have been able to get the hostname to change if I put a few delay calls such as this:

WiFi.begin(...);
delay(1);
WiFi.setHostname(...);
delay(1);
Serial.println(WiFi.getHostname());

@sethdeckard
Copy link

Issue needs to be reopened.

@urmel79
Copy link

urmel79 commented Jan 28, 2020

Hi all,
same here ... I tried all possible combinations and also the crappy workaround with delay(150) after Wifi.begin().
I'm using Node MCU ESP-32S.
Would be cool, if it could be fixed :)

Cheers,
Bjoern.

For detailed infos on my chip:
$ esptool.py --port /dev/ttyUSB0 flash_id

esptool.py v2.7
Serial port /dev/ttyUSB0
Connecting........_____....._____....._____....._
Detecting chip type... ESP32
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz
MAC: aa:bb:cc:dd:ee:ff
Uploading stub...
Running stub...
Stub running...
Manufacturer: 5e
Device: 4016
Detected flash size: 4MB
Hard resetting via RTS pin...

@me-no-dev
Copy link
Member

me-no-dev commented Jan 28, 2020

https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WiFiIPv6/WiFiIPv6.ino#L79
This is how and when you set the host name. Same goes for ETH. It has always worked that way :)

The first time the device connected to the router, I was not able to see the name, but after rest and reconnect, the name showed up.

Cheers

@richard-scott
Copy link

@urmel79 - you need to put a delay after each and every modification you make to the WiFi stack otherwise the code doesn't allow background tasks to run, and hence why the name doesn't get changed.

Post the code you say doesn't work and I'll test it on my devices.

@urmel79
Copy link

urmel79 commented Jan 29, 2020

@richard-scott and @me-no-dev :
thank your for your good hints. The delay-trick I used before also on esp8266. To set the hostname in the SYSTEM_EVENT_STA_START branch of the WiFiEvent case was new to me - so I tried it also.

I also tried on different wifi routers (both with OpenWrt, but different versions and hardware) - result: in no case the hostname was set and visible in the dhcp lease. With esp8266 I never had this problem - it worked on every wifi router in my lab like a dream ...

Here is a screenshot of the OpenWrt overview:
esp32_dhcp-lease_no_hostname
With every reset of the esp32 the dhcp lease is also renewed - the "Leasetime remaining" is resetted.
In the next post I will show you my test code.

It would be really great if you could nudge me in the right direction :)
Thank you in advance.

Cheers,
Björn.

@urmel79
Copy link

urmel79 commented Jan 29, 2020

//
// Adapted from:
// https://github.com/marvinroger/async-mqtt-client/blob/master/examples/FullyFeatured-ESP32/FullyFeatured-ESP32.ino
//
// Hint: Ticker is used and not timers from FreeRTOS (because there are tickers available in ESP32 in the meantime ...)
//

#include <WiFi.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>

#define WIFI_SSID "my_SSID"
#define WIFI_PASSWORD "my_Pwd"

#define MQTT_HOST "RaspiB3PiFaceExp"
#define MQTT_PORT 1883
#define MQTT_ROOT_TOPIC "test"
#define HOSTNAME "NodeMCU_LoRa_2_ESP32"

AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;
Ticker wifiReconnectTimer;

Ticker mqtt_pub_wifi_quality;
uint8_t g_ui_cnt = 0;
Ticker mqtt_pub_counter;

void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  // Alternative 1:
  // [Bug:] hostname cannot be set in the moment => bug in Wifi class?
  //  issue: https://github.com/espressif/arduino-esp32/issues/806
  delay(150);
  WiFi.setHostname(HOSTNAME); // set hostname
}

void connectToMqtt() {
  Serial.println("Connecting to MQTT...");
  mqttClient.connect();
}

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
  switch(event) {
  case SYSTEM_EVENT_STA_START:
    // // Alternative 2:
    // // set sta hostname here
    // WiFi.setHostname(HOSTNAME);
    break;
  case SYSTEM_EVENT_STA_GOT_IP:
    Serial.println("Connected to Wi-Fi.");

    Serial.print("ESP32 hostname: ");
    Serial.println(String(WiFi.getHostname()));
    Serial.print("ESP32 MAC: ");
    Serial.println(WiFi.macAddress());
    Serial.print("ESP32 IP: ");
    Serial.println(WiFi.localIP());
    Serial.print("Wi-Fi signal level: ");
    Serial.println(WiFi.RSSI());

    connectToMqtt();
    break;
  case SYSTEM_EVENT_STA_DISCONNECTED:
    Serial.println("Disconnected from Wi-Fi.");
    mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
    wifiReconnectTimer.once(2, connectToWifi);
    break;
  }
}

void mqttPub_wifi_rssi() {
  bool send_success;

  // convert int to string
  String str_wifi_rssi_dBm = "Wifi RSSI: " + String(WiFi.RSSI()) + " dBm";

  String topic_pub = String(MQTT_ROOT_TOPIC);
  topic_pub += "/wifi/rssi";

  if (mqttClient.connected()) {
    send_success = mqttClient.publish(topic_pub.c_str(), 0, true, str_wifi_rssi_dBm.c_str());

    if (send_success) {
      Serial.println(str_wifi_rssi_dBm);
    }
    else Serial.println("MQTT: Error sending message.");
  }
}

void mqttPub_cnt() {
  bool send_success;

  // convert int to string
  String str_cnt = "Counter: " + String(g_ui_cnt);

  String topic_pub = String(MQTT_ROOT_TOPIC);
  topic_pub += "/cnt";

  if (mqttClient.connected()) {
    send_success = mqttClient.publish(topic_pub.c_str(), 0, true, str_cnt.c_str());
    g_ui_cnt++;

    if (send_success) {
      Serial.println(str_cnt);
    }
    else Serial.println("MQTT: Error sending message.");
  }
}

void onMqttConnect(bool sessionPresent) {
  Serial.println("Connected to MQTT.");
  Serial.print("Session present: ");
  Serial.println(sessionPresent);
  uint16_t packetIdSub = mqttClient.subscribe("test/lol", 2);
  Serial.print("Subscribing at QoS 2, packetId: ");
  Serial.println(packetIdSub);
  mqttClient.publish("test/lol", 0, true, "test 1");
  Serial.println("Publishing at QoS 0");
  uint16_t packetIdPub1 = mqttClient.publish("test/lol", 1, true, "test 2");
  Serial.print("Publishing at QoS 1, packetId: ");
  Serial.println(packetIdPub1);
  uint16_t packetIdPub2 = mqttClient.publish("test/lol", 2, true, "test 3");
  Serial.print("Publishing at QoS 2, packetId: ");
  Serial.println(packetIdPub2);

  mqtt_pub_wifi_quality.attach(2, mqttPub_wifi_rssi);
  mqtt_pub_counter.attach(2, mqttPub_cnt);
}

void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
  Serial.println("Disconnected from MQTT.");

  if (WiFi.isConnected()) {
    mqttReconnectTimer.once(2, connectToMqtt);
  }
}

void onMqttSubscribe(uint16_t packetId, uint8_t qos) {
  Serial.println("Subscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
  Serial.print("  qos: ");
  Serial.println(qos);
}

void onMqttUnsubscribe(uint16_t packetId) {
  Serial.println("Unsubscribe acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
  Serial.println("Publish received.");
  Serial.print("  topic: ");
  Serial.println(topic);
  Serial.print("  payload: ");
  Serial.println(payload);
  Serial.print("  qos: ");
  Serial.println(properties.qos);
  Serial.print("  dup: ");
  Serial.println(properties.dup);
  Serial.print("  retain: ");
  Serial.println(properties.retain);
  Serial.print("  len: ");
  Serial.println(len);
  Serial.print("  index: ");
  Serial.println(index);
  Serial.print("  total: ");
  Serial.println(total);
}

void onMqttPublish(uint16_t packetId) {
  Serial.println("Publish acknowledged.");
  Serial.print("  packetId: ");
  Serial.println(packetId);
}

void setup() {
  Serial.begin(9600);
  Serial.println();
  Serial.println();

  WiFi.onEvent(WiFiEvent);

  mqttClient.onConnect(onMqttConnect);
  mqttClient.onDisconnect(onMqttDisconnect);
  mqttClient.onSubscribe(onMqttSubscribe);
  mqttClient.onUnsubscribe(onMqttUnsubscribe);
  mqttClient.onMessage(onMqttMessage);
  mqttClient.onPublish(onMqttPublish);
  mqttClient.setServer(MQTT_HOST, MQTT_PORT);

  connectToWifi();
  g_ui_cnt = 0;
}

void loop() {
}

systemofapwne added a commit to systemofapwne/Matrix-Voice-ESP32-MQTT-Audio-Streamer that referenced this issue Feb 11, 2020
…RT instead

* Experimental implementation to reflect hostname of ESP32 in the network (must be further tested) - See also espressif/arduino-esp32#806
@danielfaust
Copy link

See the solution from this issue #2537

It is unrelated to delay, WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE); needs to be called.

@urmel79
Copy link

urmel79 commented Apr 27, 2020

@danielfaust: Sorry for the late reply ... but in those times I had other priorities than playing with ESPs ...

But finally I tried your suggestion - it works! I can't explain why, but the hostname is set and updated correctly. Thanks a lot :)

So my updated connectToWifi() function looks like this:

void connectToWifi() {
  Serial.println("Connecting to Wi-Fi...");
  WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE); // call is only a workaround for bug in WiFi class
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  // Alternative 1:
  // [Bug:] hostname cannot be set in the moment => bug in Wifi class?
  //  issue: https://github.com/espressif/arduino-esp32/issues/806
  //  workaround: call 'WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);' before 'WiFi.begin(..)'
  //              suggestion found here: https://github.com/espressif/arduino-esp32/issues/2537
  WiFi.setHostname(HOSTNAME); // set hostname
}

Cheers,
Björn.

@bibinandrews
Copy link

bibinandrews commented May 3, 2020

Host name should be set only after WiFi.begin().
If host name is set before begin() then seems the API(WiFi.begin()) is overwriting the host name set before with default (which is ESP_xxxx).

Hence the host name needs to be set after WiFi.begin()

For me setting the host name after WiFi.begin() works.... There is no other magic inside like doing the config and all to get it work

@fbernaly
Copy link

This is my code

void setup(){
  Serial.begin(115200);
  Serial.println("");
  Serial.print("connecting to ");
  Serial.print(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  WiFi.setHostname(hostname);

  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("connected.");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Hostname: ");
  Serial.println(WiFi.getHostname());

  server.begin();
}

Serial monitor prints the hostname I set, but when I got to the Terminal to run ping <my_hostname> it cannot find it.

$ ping esp32test
ping: cannot resolve esp32test: Unknown host

Any idea?

@bibinandrews
Copy link

bibinandrews commented May 22, 2020

The issue is not because of the host name, but the DNS resolver issue.
When you ping esp32test (which is the name), the laptop / desktop from where you issued the ping command sends "esp32test" name to the DNS server (Primary / secondary) to resolve the name. This would obviously fail as the DNS server on your laptop would be mapped to an DNS server on internet.

The way to solve the issue is

  1. on ESP32 add the mDNS library and configure the same (Good level of documentation is available for the same). mDNS is an implementation for local hosts through a multicast network.
  2. ping to esp32test.local. Any domain ending with .local would result in the mDNS resolution, which would map is to your ESP32

Note:- Android do not support mDNS, hence it may not work on Android based devices.

Wish you all the success on your project!!!!

@kishieel
Copy link

Not sure if it help everyone but in my case this code works in most of situations. Sometimes, maybe 1 per 20 something crash and esp doesn't have any hostname.

#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>

const char * hostname = "ezakr";

void setup( void ) {
    Serial.begin( 115200 );
    while( ! Serial ) { };

    WiFi.disconnect();
    WiFi.mode( WIFI_STA );
    WiFi.begin( "Tomek", "16122000" );
    WiFi.setHostname( hostname );
    WiFi.setAutoReconnect( true );

    if ( WiFi.waitForConnectResult() == WL_CONNECTED ) {
        Serial.println( "Achive wifi connection" );
    } else {
        Serial.println( "Wifi connection failed!" );
    }

}

void loop( void ) {
    if ( WiFi.status() == WL_CONNECTED ) {
        HTTPClient client;

        Serial.println( "Request sending!" );
        client.begin( "http://192.168.55.102:8000/test" );   // I also use it on normal server url address and everything works well
        uint16_t status = client.GET();

        if ( status == 200 ) {
            Serial.println( "Request response:" );
            Serial.println( client.getString() );
        } else {
            Serial.println( "Request failed!" );
        }

        client.end();
    } else {
        Serial.println( "No wifi connection!" );
    }

    delay( 2000 );
} 

Honestly, this code only works well if your esp isn't doing a lot more other things. When you start adding other tasks, everything starts to break and esp crashes and resets.

Use it wisely .. happy carroting :3

@JBFUK
Copy link

JBFUK commented Aug 17, 2020

See the solution from this issue #2537

It is unrelated to delay, WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE); needs to be called.

This fixed it for me too.

@slashinpdx
Copy link

slashinpdx commented Oct 24, 2023

Working with an ESP32 WROOM 32
I did some testing and found that if I put the lines in this order:
Wifi.setHostname(hostname);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
that the router would receive the correct host name when registering with DHCP.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests