-->
Page 1 of 2

Obtaining IP Address

PostPosted: Thu Mar 24, 2016 10:14 am
by cadywompus
I'm trying to find a way to get the IP address of the server that I'm connected to. I need this in order to use an esp-link program to read data via MQTT.

Headers included in my code
ESP8266WIFI.h
PubSubClient.h

I also create a WiFiClient object.

From what I've looked at in their source code, WiFiClient has a function built in called remoteIP that seems like it may do what I need. Then there is the getIP function in ESP8266WiFi.h; however, I don't know if this just gets the local IP address of the device, the wifi access point, or the server.

Which of these is the best way to get me where I'm trying to go, or is there a better, easier way to do this? :)

Re: Obtaining IP Address

PostPosted: Thu Mar 24, 2016 11:41 am
by martinayotte
The remoteIP() of WiFiClient is only to get the IP of a client that is currently connected to a WiFiServer running on the ESP.
If you wish only to get the IP of an remove server, simply use the WiFi.hostByName().

Re: Obtaining IP Address

PostPosted: Thu Mar 24, 2016 3:42 pm
by cadywompus
So for this hostByName() function in ESP8266WiFi.h, do I pass through the server name and it returns the IP address as an integer? I'm a little rusty when it comes to class and object coding.

Would it be called like I've written below?

int serverIP = wificlient.hostByName(server.serv);

Re: Obtaining IP Address

PostPosted: Fri Mar 25, 2016 7:55 am
by martinayotte
No ! you need to pass an IPAddress pointer, it will be filled, then, the return integer tell you if succeded.

Code: Select all/**
 * Resolve the given hostname to an IP address.
 * @param aHostname     Name to be resolved
 * @param aResult       IPAddress structure to store the returned IP address
 * @return 1 if aIPAddrString was successfully converted to an IP address,
 *          else error code
 */
int ESP8266WiFiGenericClass::hostByName(const char* aHostname, IPAddress& aResult) {


Code: Select allIPAddress ipaddr;
if (WiFi.hostByName("google.com", &ipddr) = 1) {
    Serial.println(String("IP is ") + ipaddr);
}