What is the gateway IP address for localhost? - arduino

I am trying to setup my ESP32-arduino Web server to localhost on port 8080.
What should I mention for the gateway IP address?
My current code is as follows:
IPAddress staticIP(127, 0, 0, 1);
IPAddress gateway(127, 0, 0, 1);
IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8); //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional
if (WiFi.config(staticIP, gateway, subnet, primaryDNS, secondaryDNS) == false) {
Serial.println("Configuration failed.");
}

I'm not really sure what you're trying to do here, but there is no gateway for "localhost".
127.0.0.1 and "localhost" mean self. They are not meant to be routable or externally reachable.
You need to use the correct public IP address of a network interface on whatever computer or server you're trying to reach. "localhost" and 127.0.0.1 are not it.

Related

How can I recieve packets on an ESP32 over multicast with EthernetUDP?

I am using an ESP32 and would like to send and receive messages a multicast address. Right now I am using very similar code to the WifiUDP example (https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/udp-examples.html). I am currently using multicast ip address: 239.0.0.0 though I've tried others such as (224.0.0.0).
In order to test the code I'm using PacketSender to send to the multicast address above and do not recieve any messages through the ESP32. Image to Packet Sender Multicast Example
However, when I change my address to the device's ip: 10.0.0.21, I see it print in the Serial Monitor that a message has been received. I am unsure what is the issue regarding multicast, and where the error may be in receiving messages.
My code is below:
void setup() {
Serial.begin(115200);
Ethernet.init(5);
Ethernet.begin((uint8_t *)mac, ip);
Ethernet.setRetransmissionCount(0);
Ethernet.setRetransmissionTimeout(0);
Udp.beginMulticast(multicastGroup, port);
Serial.println("Multicast has began.");
}
void loop() {
//Recieve Packets
int packetSize = Udp.parsePacket();
if (packetSize) {
// receive incoming UDP packets
Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(incomingPacket, 255);
if (len > 0) {
incomingPacket[len] = 0;
}
Serial.printf("UDP packet contents: %s\n", incomingPacket);
// send back a reply, to the IP address and port we got the packet from
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Serial.print("Sending message back to IP: ");
Serial.print(Udp.remoteIP());
Serial.print(" Port: ");
Serial.println(Udp.remotePort());
Udp.write(replyPacket);
Udp.endPacket();
}
}

Arduino ESP32 DHCP server

I searched how to configure a DHCP server on ESP32 Arduino to distribute addresses for clients that connect to my ESP32 access point, but unfortunately I did not get any source code for that.
Any help?
As long as you use WiFi.softAP(), you do not need to explicitly configure a DHCP server on the ESP32. It will happen automatically - the library looks after it for you.
Here is a minimal example, where - in addition to setting the ESP32 up as an access point - a TCP server is also started on port 80.
WiFiServer server(80);
static const char *ap_ssid = "ESP32-001";
static const char *ap_pass = "temp_pass";
void setup() {
Serial.begin(115200);
WiFi.softAP(ap_ssid, ap_pass);
Serial.print("Access point running. IP address: ");
Serial.print(WiFi.softAPIP());
Serial.println("");
server.begin();
}
void loop() {
WiFiClient client = server.available();
if (client) {
String client_ip = client.remoteIP().toString();
Serial.print("Client connected. IP address = ");
Serial.print(client_ip);
Serial.println("");
client.println("Hello ...");
client.stop();
}
}
I have attached the serial output in a screenshot below. Notice the
dhcps: send_offer>>udp_sendto result 0
message.

mbedtls_net_connect returned -0x52 when connecting to AWS IoT using ESP32 in Arduino IDE

I am trying to connect to AWS IoT using a basic pubsub example in my ESP32 board with the help of the Arduino IDE.
As a basic example it does connect to AWS IoT and publishes messages, but when I give a static IP to the program it does connect to the wifi with the specified IP address (I have also assigned a static IP to the MAC address of the board in my router), but it fails to publish the messages and gives me the following error:
Attempting to connect to SSID: RCB Rocks!!!!
Connected to wifi
E (37583) aws_iot: failed! mbedtls_net_connect returned -0x52
E (37583) AWS_IOT: Error(-23) connecting to ***********.iot.eu-west-2.amazonaws.com:8883,
Trying to reconnect
I am using the following code:
#include <AWS_IOT.h>
#include <WiFi.h>
AWS_IOT hornbill;
char WIFI_SSID[]="RCB Rocks!!!!";
char WIFI_PASSWORD[]="********";
char HOST_ADDRESS[]="************.iot.eu-west-2.amazonaws.com";
char CLIENT_ID[]= "1008";
char TOPIC_NAME[]= "smk";
IPAddress ip(192, 168, 0, 20);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);
int status = WL_IDLE_STATUS;
int tick=0,msgCount=0,msgReceived = 0;
char payload[512];
char rcvdPayload[512];
void mySubCallBackHandler (char *topicName, int payloadLen, char *payLoad) {
strncpy(rcvdPayload,payLoad,payloadLen);
rcvdPayload[payloadLen] = 0;
msgReceived = 1;
}
void setup() {
Serial.begin(115200);
delay(2000);
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(WIFI_SSID);
WiFi.config(ip,gateway,subnet);
WiFi.mode(WIFI_STA);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
// wait 5 seconds for connection:
delay(5000);
}
Serial.println("Connected to wifi");
if(hornbill.connect(HOST_ADDRESS,CLIENT_ID)== 0) {
Serial.println("Connected to AWS");
delay(1000);
if(0==hornbill.subscribe(TOPIC_NAME,mySubCallBackHandler)) {
Serial.println("Subscribe Successfull");
} else {
Serial.println("Subscribe Failed, Check the Thing Name and Certificates");
while(1);
}
} else {
Serial.println("AWS connection failed, Check the HOST Address");
while(1);
}
delay(2000);
}
void loop() {
if(msgReceived == 1) {
msgReceived = 0;
Serial.print("Received Message:");
Serial.println(rcvdPayload);
}
if(tick >= 5) {
// publish to topic every 5seconds
tick=0;
sprintf(payload,"Hello from hornbill ESP32 : %d",msgCount++);
if(hornbill.publish(TOPIC_NAME,payload) == 0) {
Serial.print("Publish Message:");
Serial.println(payload);
} else {
Serial.println("Publish failed");
}
}
vTaskDelay(1000 / portTICK_RATE_MS);
tick++;
}
I have found this AWS IoT SDK for Arduino ESP32 here, and I followed the instructions given in this website.
Attempting to connect to SSID: RCB Rocks!!!! Connected to wifi
So your board is able to get a network connection.
E (37583) aws_iot: failed! mbedtls_net_connect returned -0x52
This error means
NET - Failed to get an IP address for the given hostname
Either the host name is wrong or there's something wrong with your DNS setup. Given that your program works when you don't use a static IP address, the problem must be with the DNS setup on the board. When the board receives a dynamic IP address from DHCP, the DHCP server also sends it DNS settings. If you use a static IP address instead of DHCP, you also need to set up a DNS server statically.
You might want to try seeing if the ESP board can even connect to the internet using that static IP. You could try running this sketch. https://learn.sparkfun.com/tutorials/esp32-thing-hookup-guide#arduino-example-wifi
I had the same issue on my board and was getting the DNS_PROBE_FINISHED_NO_INTERNET if I connected to the wireless from chrome. Changing to a different network fixed the issue.
I know this is old, but moving Wifi.begin() outside the for loop did the trick for me:
WiFi.config(ip,gateway,subnet);
WiFi.mode(WIFI_STA);
Serial.print("Attempting to connect to SSID: ");
Serial.println(WIFI_SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.print("connected.");

ESP8266 send UDP string to AP

I am using UDP to connect two nodemcu modules. One nodemcu is wireless acces point and another nodemcu connects to access point as client.
This code sends client's IP adress to AP when client connects:
Udp.beginPacket("192.168.4.1", UDPPort);//send ip to server
char ipBuffer[20];
WiFi.localIP().toString().toCharArray(ipBuffer, 20);
Udp.write(ipBuffer);
Udp.endPacket();
Serial.println("Sent ip adress to server");
But on the server side I don't recieve this packet.
Client:
#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
unsigned int UDPPort = 2390; // local port to listen on
char packetBuffer[255]; //buffer to hold incoming packet
char replyBuffer[] = "acknowledged"; // a string to send back
WiFiUDP Udp;
void setup() {
Serial.begin(115200);
WiFi.begin("Wi-Fi");
Serial.println();
Serial.print("Wait for WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: " + WiFi.localIP().toString());
Udp.begin(UDPPort);
Udp.beginPacket("192.168.4.1", UDPPort);//send ip to server
char ipBuffer[255];
WiFi.localIP().toString().toCharArray(ipBuffer, 255);
Udp.write(ipBuffer);
Udp.endPacket();
Serial.println("Sent ip adress to server");
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(replyBuffer);
Udp.endPacket();
}
}
Server:
#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
unsigned int UDPPort = 2390; // local port to listen on
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = "acknowledged"; // a string to send back
WiFiUDP Udp;
void setup() {
Serial.begin(115200);
WiFi.softAP("Wi-Fi");
Udp.begin(UDPPort);
Serial.println();
Serial.println("Started ap. Local ip: " + WiFi.localIP().toString());
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
}
Another thing doesn't work: If I send a packet from another device connected to AP nodemcu to client nodemcu(also connected to AP), packet is recieved, but I get no acknowledgement reply back to device.
Everything else works - If i send a packet from another device to AP nodemcu, packet is recieved and i get acknowledgement.
Also, if I connect to my home wi-fi router with client nodemcu and listen for packet from my pc, i get client's ip adress when it connects.
I got exactly the same problem. I've just solve it. Your code is almost the same as mine.
All ESP- modules can be AP and station.
That means, a ESP module has local network for itself.
In my case, client module(ESP) is station mode and server module(ESP) is SoftAP mode.
The ip of the server module is 192.168.4.9 and I set the ip of gateway is 192.168.4.1.
When client module connected to the AP of server module, the ip of client was 192.168.4.103, and then i tried to send udp packets from the client module to the AP. Nothing happened but when i send the same packet from other device such as pc it worked.
I tried to access the AP of server module on my laptop. I found a wired SSID the name was 'EPS_4510DB'. It was actually the client module's one. The gateway ip of ESP_4510DB was 192.168.4.1.
Suddenly I realised the network of client module's AP and of server module's AP is the same, and the client module(for station)'s network linked its own AP network.
In other word, the client module sent udp packets to AP's network of itself instead of one of the server module.
So i changed the ip and i was able to send udp packets to server module.
And as #Barry Bea mentioned, I think you can also disable the AP of client module by using WiFi.mode(WIFI_STA) in client module, not server module.
I hope it helps someone~
I had to change port numbers for each conected esp8266. If IP of esp was 192.168.4.2, I set port to 2302, for 192.168.4.3, I set it to 2303...
I have painstakingly been trying to trouble shoot a similar problem...
I too could not get any packages sent by my ESP8266's
I changed your line;
WiFi.softAP("Wi-Fi");
to ....
WiFi.mode(WIFI_STA);
works EVERY TIME now....with no package loss..

Windows 7 upgrade, UDP Broadcast issue

I am new to this environment as far as UDP protocols and sending/receiving data via networks. I have read the other post regarding this kind of issue but I am not sure how to fix my problem:
I have just upgraded a PC to Windows 7 from XP. This upgrade was due to my application needs to run on Win7. I have NOT changed the was our UDP stream is broadcasted. With the upgrade I can no longer run the older version of my application becasue the UDP stream doesn't seam to get to my application.
I have turned off all firewalls and am running everything as admin.
This is how my setup is:
Code is running on ip: 192.168.2.1
UDP is sent from 192.168.2.1 to 192.168.2.87 and then broadcasted to 192.168.2.255
I used to be able to see this UDP stream with my old application on a seperate computer: 192.168.2.12
If I change my UDP stream to go directly to 192.168.2.12 ip, then my application works, but then the UDP is not broadcasted anymore. I need the UDP to be able to be read by more than one computer.
Here is my wireshark out put for the UDP Stream:
Source: 192.168.2.87
Destination: 192.168.2.255
Protocol: UDP Info:
Sorce Port: 6601 Destination Port: 6601
I have tried hard coding my c-code to listen to any possibility I can think of, aka the sender addr function:
senderAddr.sin_addr.s_addr = htonl(INADDR_ANY);
To something like:
senderAddr.sin_addr.s_addr = inet_addr("192.168.2.212")
This is the code to init the I/O buffer:
// UDP Receiver Declarations -
SOCKET SockIn = INVALID_SOCKET;
SOCKADDR_IN senderAddr;
int senderSize = sizeof(senderAddr);
u_short PortIn = 6601;
int timeout = 1;
//===================<Callbacks::Callbacks>==================
//
// Summary: Constructor
//
//=============================================================================
Callbacks::Callbacks(RTUserIntegrationI &a_rIntegration)
: m_rIntegration(a_rIntegration)
, m_pUDPInput(NULL)
{
}
//=====================<Callbacks::~Callbacks>===============
//
// Summary: Destructor
//
//=============================================================================
Callbacks::~Callbacks()
{
}
//=====================<Callbacks::InitIOBuffers>====================
//
// Summary: Init function for the IO buffer
//
//=============================================================================
void Callbacks::vInitIOBuffers()
{
BOOL bOptVal = TRUE;
int bOptLen = sizeof(BOOL);
WSADATA WSAData;
UInt Size = 0;
// UDP Declarations -
// Initialize the member pointers to buffers
bufferin = m_rIntegration.pGetIOBuffer(Input_Buffer);
if (bufferin != NULL)
m_pUDPInput = static_cast<InputData*>(bufferin->pGetDataAddress(Size));
// UDP Receive -
if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
{
printf("\nCould not open WSA connection");
WSACleanup();
}
SockIn = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (SockIn == INVALID_SOCKET)
{
printf("\nCould not create socket.");
closesocket(SockIn);
WSACleanup();
}
senderAddr.sin_family = AF_INET;
senderAddr.sin_port = htons(PortIn);
senderAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (setsockopt(SockIn, SOL_SOCKET, SO_REUSEADDR, (char*)&bOptVal, bOptLen) != INVALID_SOCKET)
{
printf("\nSet SO_REUSEADDR: ON.");
}
if (bind(SockIn, (struct sockaddr *) &senderAddr, senderSize) == -1)
{
printf("\nCould not bind socket.");
closesocket(SockIn);
WSACleanup();
}
setsockopt(SockIn, SOL_SOCKET, SO_RCVTIMEO, (char*) &timeout, sizeof(timeout));
}
I have the receive port number hard coded to 6601.
The code above works fine and the computer sees and reads the broadcasted UDP in Windows XP but ceases to work in Windows 7.
Any suggestions would be greatly appreciated.
ADDED:
192.168.2.1 generates the UDP stream--->sent to 192.168.2.87---> broadcasted on 192.168.2.255 ---> Notheing has changed on any of those computers....... I then have two computers (one XP and one Windows 7) than listen to the 2.255 ip. XP is getting the UDP and Win7 is not.

Resources