Cannot connect to LocalIP or Localhost (127.0.0.1) Using Arduino ESP8266 or Compatible Boards - tcp

I am trying to connect my Arduino ESP8266 or any of the compatible boards like WeMos mini or NodeMCU to my local server, either localhost(127.0.0.1) or 172.xx.xx.xxx port 80.
I get an httpResponseCode -1 error. But if I have it connected to a remote server I get an httpResponseCode 200 (OK).
I am running an XMPP server (even tested with Coldfusion server). My code is as below. Can anybody help?
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
const char* ssid = "ssid";
const char* password = "password";
//Your Domain name with URL path or IP address with path
String serverName = "http://stackoverflow.com";// returns 200 (ok results)
//String serverName = "127.0.0.1"; // Gives -1 error, Tried IP addresses with 172.xx.xx.xx or even 192.168.xx.xx.
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
// unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
//Send an HTTP POST request every 10 minutes
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if (WiFi.status() == WL_CONNECTED){
HTTPClient http;
String serverPath = serverName + "?temperature=24.37";
// Your Domain name with URL path or IP address with path
//http.begin(serverPath.c_str());
http.begin(serverName);
// Send HTTP GET request
int httpResponseCode = http.GET();
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.println(payload);
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
} else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}

The address 127.0.0.1 is the Arduino itself, not your local server.
Every host/computer with an IP address also has an IP address 127.0.0.1; it is the address of the loopback interface.
This localhost address always refers to the current computer. The Arduino also has this address, and you are trying to connect to it.
Use the IP address of your XMPP server; find out what the address is first, that works much better than guessing and trying.

Related

Esp8266 Http communication over Wifi

Goal
I am trying to send temperature data between two Esp8266 modules.
The Server reads a temperature value from the analog pin and is supposed to host this data on a website (I don´t know the correct term for that) over a wifi access point that also runs on the Esp. The Client is supposed to receive the temperature value and output it via serial.
What works
I can connect my phone to the access point and access the data on the IP of the access point. I also can connect the client Esp to my home wifi and it outputs code from different websites.
Problem
But when I try to connect it to the Esp wifi, the wifi login/connection works, but the http.GET function outputs -1 which corresponds to the error message "HTTPC_ERROR_CONNECTION_FAILED".
While the client is connected to the wifi of the Esp my phone displays a similar error message.
I also had the problem that the esp could not continually read A0 while using the Wifi, so I had to build in a delay.
Server Code
// Import required libraries
#include "ESPAsyncWebServer.h"
#include "WiFi.h"
#include <math.h>
#include <ESP8266WiFi.h>
//Constants for temperature calculation
double T;
float V_0 = 5.02;
float R_1 = 99700.0;
float a = 283786.2;
float b = 0.06593;
float c = 49886.0;
float set = 30;
int sensorValue;
float voltage;
// Set your access point network credentials
const char* ssid = "ESP32-Access-Point";
const char* password = "123456789";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
String readTemp() {
return String((-1.0/b)*(log(((R_1*voltage)/(a*(V_0-voltage)))-(c/a)))); //Function to calculate temperature from Voltage
}
void setup(){
Serial.begin(115200);
Serial.println();
// Setting the ESP as an access point
Serial.print("Setting AP (Access Point)…");
// Remove the password parameter, if you want the AP (Access Point) to be open
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readTemp().c_str());
});
// Start server
server.begin();
}
void loop()
{
//reading of A0
Serial.println(voltage);
Serial.println(readTemp().c_str());
sensorValue = analogRead(0); //?Wifi not working, when reading A0?
delay(10);
voltage = sensorValue * (3.3 / 1023.0);
}
Client Code
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "ESP32-Access-Point";
const char* password = "123456789";
void setup () {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting..");
}
Serial.print("Connected to ");
Serial.println(ssid);
}
void loop() {
if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
HTTPClient http; //Declare an object of class HTTPClient
http.begin("http://192.168.4.1/temperature"); //Specify request destination
int httpCode = http.GET(); //Send the request
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println("/////////////////////////////////////////////////////////////");
Serial.println(payload); //Print the response payload
}
else{Serial.println("Error");}
http.end(); //Close connection
}
delay(30000); //Send a request every 30 seconds
}
I would really appreciate it if anybody could help me with this because I have been tearing my hair out for weeks over this. Thanks in advance and sorry for any grammatical or spelling mistakes in advance.

getting arduino ethernet shield to work?

I've recently bought an Arduino ethernet shield but couldn't get it work.
I've tried to use the example's code but it did not work. I have even tried to get a static IP without DHCP and it's always the same problem .
I've used this code :
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0xBF };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
char server[] = "www.google.com"; // name address for Google (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,1,10);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /search?q=arduino HTTP/1.1");
client.println("Host: www.google.com");
client.println("Connection: close");
client.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while(true);
}
}
and I got this answer:
Failed to configure Ethernet using DHCP
connecting...
connected
disconnecting.
How can I be sure that my ethernet shield is working correctly and how can I resolve this problem?
With a failed DHCP you don't have DNS address to resolve "www.google.com".
Modify your code like this and try again :
IPAddress server(74,125,232,128);
//char server[] = "www.google.com";

simple web server nort working with arduino wifi shield

I have recently bought an arduino wifi shield(Atmal chip 32UC3A1512-U), which I connected with
my Arduino Mega ADK R3 board)...It is getting connected to my wifi network, But when I run the
SimpleWebServer Example provided in the library to on/off the LED is not working. The code is given below...
#include <SPI.h>
#include <WiFi.h>
char ssid[] = "belkin.E33"; // your network SSID (name)
char pass[] = "abc123cde456"; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
Serial.begin(9600); // initialize serial communication
pinMode(9, OUTPUT); // set the LED pin mode
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while(true); // don't continue
}
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin(); // start the web server on port 80
printWifiStatus(); // you're connected now, so print out the status
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("new client"); // print a message out 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
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();
// the content of the HTTP response follows the header:
client.print("Click here turn the LED on pin 9 on<br>");
client.print("Click here turn the LED on pin 9 off<br>");
// 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
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
digitalWrite(9, HIGH); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
digitalWrite(9, LOW); // GET /L turns the LED off
}
}
}
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}
The result that I am getting in the serial monitor is
Attempting to connect to Network named: belkin.E33
SSID: belkin.E33
IP Address: 192.168.2.5
strength (RSSI):-56 dBm
To see this page in action, open a browser to http://192.168.2.5
But When I am opening the browser with the specified IP address, It is showing
Could not Connect to 192.168.2.5
I have tried this in mozilla and chrome from my ubuntu machine...also tried from some other machines in the same network but with the same result. But when I am pinging to 192.168.2.5 it is pinging...What went wrong??? . My friend adviced to change the firmware...Is it an issue,bcas as told earlier simple examples for establishing the connection are working...Please guide me
I've got the same problem after upgrading Arduino IDE to lastest version (v2) from v1.0.8 which is doing fine with the wifi shield tests (client and server).
Going to try the nightly build now and see if it's fixed.
Edit: Yeap, Nightly build solves this issue.

Arduino DHCP error

I'm testing the Ethernet shield with an Arduino Uno, and I'm getting a DHCP error just using the example sketch.
#include <SPI.h>
#include <Ethernet.h>
byte MACaddress[] = { 0x90, 0xAD, 0xDA, 0x0D, 0x96, 0xFE };
EthernetClient client;
void setup() {
Serial.begin(9600);
while (!Serial) {
;
}
// Start the Ethernet connection:
if (Ethernet.begin(MACaddress) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
Serial.print("My IP address: ");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
Serial.println();
}
void loop() {
}
I've opened the router administration page, and I can see it gave the Arduino an IP address, associated with the MAC address. I've also tried a static IP address in the code (Ethernet.begin(MACaddress, IPaddress)), but it won't work either.
I can't ping the shield IP address that shows in the router administrator page.
What is wrong with just this simple code?
Everything is out of the box, the Arduino and the shield. I haven't done anything with them, just connected the shield to the Arduino and sent the code. It seems everything is working fine, the LEDs are blinking for both boards.
These loops are useless.. Could you try something like:
#if defined(ARDUINO) && ARDUINO > 18
#include <SPI.h>
#endif
#include <Ethernet.h>
#include <EthernetDHCP.h>
// MAC Address
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
const char* ip_to_str(const uint8_t*);
// Initialize the Ethernet server library
Server server(8080);
void setup()
{
Serial.begin(9600);
Serial.println("Attempting to obtain a DHCP lease...");
// Initiate a DHCP session. The argument is the MAC (hardware) address that
// you want your Ethernet shield to use. This call will block until a DHCP
// lease has been obtained. The request will be periodically resent until
// a lease is granted, but if there is no DHCP server on the network or if
// the server fails to respond, this call will block forever.
// Thus, you can alternatively use polling mode to check whether a DHCP
// lease has been obtained, so that you can react if the server does not
// respond (see the PollingDHCP example).
EthernetDHCP.begin(mac);
// Since we're here, it means that we now have a DHCP lease, so we print
// out some information.
const byte* ipAddr = EthernetDHCP.ipAddress();
const byte* gatewayAddr = EthernetDHCP.gatewayIpAddress();
const byte* dnsAddr = EthernetDHCP.dnsIpAddress();
Serial.println("A DHCP lease has been obtained.");
Serial.print("My IP address is ");
Serial.println(ip_to_str(ipAddr));
Serial.print("Gateway IP address is ");
Serial.println(ip_to_str(gatewayAddr));
Serial.print("DNS IP address is ");
Serial.println(ip_to_str(dnsAddr));
// Start the server
server.begin();
}
void loop()
{
// You should periodically call this method in your loop(): It will allow
// the DHCP library to maintain your DHCP lease, which means that it will
// periodically renew the lease and rebind if the lease cannot be renewed.
// Thus, unless you call this somewhere in your loop, your DHCP lease might
// expire, which you probably do not want :-)
EthernetDHCP.maintain();
// listen for incoming clients
Client client = server.available();
if (client) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
// Some misc. HTML
client.println("<title>Arduino Control Panel</title>");
client.println("<center><h1>Control Panel</h1></center>");
client.println("<p></p>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
client.print("Analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(analogRead(analogChannel));
client.println("<br />");
}
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}
// Just a utility function to nicely format an IP address.
const char* ip_to_str(const uint8_t* ipAddr)
{
static char buf[16];
sprintf(buf, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
return buf;
}
I'm not sure what you mean by "I've also tried a static IP address in the code". If you simply replaced
if (Ethernet.begin(MACaddress) == 0) {
with
if (Ethernet.begin(MACaddress, myIP) == 0) {
the result may be unpredictable, because there is no return value.
Read
EthernetBegin
Returns
The DHCP version of this function, Ethernet.begin(mac), returns an int: 1 on a successful DHCP connection, 0 on failure. The other versions don't return anything.
have you tried one of the examples with fixed IP's?

Arduino Ethernet and DHCP cannot communicate out to the Internet

I have this web client example that gets an IP address via DHCP. It connects to my router at IP address 192.168.0.1 successfully, but then it fails to send a GET HTTP to google.com. Essentially, I cannot allow the traffic from Arduino to go out into the Internet.
I have a Linksys/Cisco E2000 router connected to the Arduino.
My code is below.
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetDHCP.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x78, 0x0B};
byte ip[] = {192, 168, 0, 125};
byte gateway[] = {192, 168, 0, 1};
byte subnet[] = {255,255,255,0};
byte serverLocal[] = { 192,168,0,1 }; // Google
byte serverExternal[] = { 173,194,33,104 }; // Google
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
Client clientLocal(serverLocal, 80);
Client clientExternal(serverExternal, 80);
const char* ip_to_str(const uint8_t*);
void setup() {
Serial.begin(9600);
Serial.println("Attempting to obtain a DHCP lease...");
// Initiate a DHCP session. The argument is the MAC (hardware) address that
// you want your Ethernet shield to use. This call will block until a DHCP
// lease has been obtained. The request will be periodically resent until
// a lease is granted, but if there is no DHCP server on the network or if
// the server fails to respond, this call will block forever.
// Thus, you can alternatively use polling mode to check whether a DHCP
// lease has been obtained, so that you can react if the server does not
// respond (see the PollingDHCP example).
EthernetDHCP.begin(mac);
// Since we're here, it means that we now have a DHCP lease, so we print
// out some information.
const byte* ipAddr = EthernetDHCP.ipAddress();
const byte* gatewayAddr = EthernetDHCP.gatewayIpAddress();
const byte* dnsAddr = EthernetDHCP.dnsIpAddress();
Serial.println("A DHCP lease has been obtained.");
Serial.print("My IP address is ");
Serial.println(ip_to_str(ipAddr));
Serial.print("Gateway IP address is ");
Serial.println(ip_to_str(gatewayAddr));
Serial.print("DNS IP address is ");
Serial.println(ip_to_str(dnsAddr));
// if you get a connection, report back via serial:
if (clientLocal.connect()) {
Serial.println("connected internally");
// Make a HTTP request:
clientLocal.println("GET /index.html HTTP/1.0");
clientLocal.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed internally");
}
// if you get a connection, report back via serial:
if (clientExternal.connect()) {
Serial.println("connected externally");
// Make a HTTP request:
clientExternal.println("GET /search?q=arduino HTTP/1.0");
clientExternal.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed externally");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (clientLocal.available()) {
char c = clientLocal.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!clientLocal.connected()) {
Serial.println();
Serial.println("disconnecting.");
clientLocal.stop();
}
// if there are incoming bytes available
// from the server, read them and print them:
if (clientLocal.available()) {
char c = clientLocal.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!clientExternal.connected()) {
Serial.println();
Serial.println("disconnecting.");
clientExternal.stop();
// do nothing forevermore:
for(;;)
;
}
}
// Just a utility function to nicely format an IP address.
const char* ip_to_str(const uint8_t* ipAddr)
{
static char buf[16];
sprintf(buf, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
return buf;
}
Here's an example of working code (maybe you used this as a source?). The only differences I could see are the lines:
Serial.begin(9600);
delay(1000);
just before the line:
if (clientLocal.connect()) {
I doubt the additional Serial.begin() has any effect but the delay() may be required (although it's a long shot...)

Resources