I'm new to Arduino programming. I want to make my esp8266 get static IP based on gateway.

I mean if gateway is then it should get as static IP. And if gateway is then it should get as IP.

  • Isn't that the role of DHCP? Your Access Point / Router should be handing out that IP address. If you want it to be static then configure your router to allocate a static IP for the MAC address. If you're getting the gateway by DHCP then you will also be getting an IP through DHCP. – Majenko Sep 2 '20 at 9:02
  • I'm wondering why you would want to do that. You run the risk of IP collissions and network problems that are hard to diagnose. I would not want such a device in my network ;-) A (Static) DHCP Address reservation is the mechanism you should be using. – StarCat Sep 2 '20 at 13:09

You can either set the router to allocate a static IP based on your esp8266's MAC address, or go the DHCP-way first, read the gateway IP address you got, and then do a WiFi.config(), something roughly like this (untested):

WiFi.begin(ssid, password);
IPAddress ip = WiFi.gatewayIP();
IP[3] = 15;
IPAddress dns(8, 8, 8, 8);
WiFi.config(ip, WiFi.gatewayIP(), dns, WiFi.subnetMask());

It is a bit of a trick, and not pretty, and you don't get to set the DNS as provided by the DHCP, because there is no getDNS(), for some silly reason, hence the use of Google DNS.

Note that when doing this, you run the risk of setting the esp8266's IP address to an address already taken by another device on the same router.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.