Can't catch UDP datagrams from NANO + ENC28J60 to pc

I can't get UDP datagrams from nano + ENC28J60 to my pc. Working with this hardware like a server is brilliant, I even can recieve dgrams and turn on/off light. But I need to know, how I can send UDP packages. Dgrams even have been seen in wireshark. Could you help me?

#include <EtherCard.h>
#include <IPAddress.h>
#include <string.h>

#define LIGHT 6

static byte myip[] = { 192,168,1,3 };
static byte gwip[] = { 10,21,224,1 };
static byte dnsip[] = { 195,98,64,65 };
static byte mask[] = {255,255,255,0};

static byte mymac[] = { 0x70,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[500]; // tcp/ip send and receive buffer

// //callback that prints received packets to the serial port
// void handler(uint16_t dest_port, uint8_t src_ip[IP_LEN], uint16_t src_port, const char *data, uint16_t len){
//   IPAddress src(src_ip[0],src_ip[1],src_ip[2],src_ip[3]);

//   Serial.println("Connection from:");
//   Serial.print("dest_port: ");
//   Serial.println(dest_port);
//   Serial.print("src_port: ");
//   Serial.println(src_port);
//   Serial.print("src_ip: ");
//   ether.printIp(src_ip);
//   Serial.println();
//   Serial.print("data: ");
//   Serial.println(data);

//   if (strcmp("1", data) == 0) {
//     digitalWrite(LIGHT, HIGH);
//   }
//   else if (strcmp("0", data) == 0) {
//     digitalWrite(LIGHT, LOW);
//   }
//   else {
//     Serial.println("Invalid command!");
//   }
// }

void setup(){
  pinMode(LIGHT, OUTPUT);

  Serial.begin(57600);
  Serial.println(F("\n[backSoon]"));

  // Change 'SS' to your Slave Select pin, if you arn't using the default pin
  if (ether.begin(sizeof Ethernet::buffer, mymac, SS) == 0)
    Serial.println(F("Failed to access Ethernet controller"));
  ether.staticSetup(myip, gwip, dnsip, mask);
  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("MASK: ", ether.netmask);
  ether.printIp("DNS: ", ether.dnsip);
  
  ether.parseIp(ether.hisip, "192.168.1.2");
  ether.printIp("HISIP: ", ether.hisip);

  // //register udpSerialPrint() to port 1234
  // ether.udpServerListenOnPort(&handler, 12345);
}

void loop(){
  //this must be called for ethercard functions to work.
  // ether.packetLoop(ether.packetReceive()); - don't work with/without it
  ether.sendUdp("1", sizeof("1"), 55555, ether.hisip, 10002);
  Serial.println("1");
  delay(1000);
}

have a read of how-to-get-the-best-out-of-this-forum
e.g.

  1. are you using a router between the ENC28j60 and PC?
  2. how do you power the ENC28j60? from the Nano?

is the light on the Nano? datagrams from where?

Thank you for your reply.

  1. I use router between ENC28j60 and PC.
  2. I power ENC28j60 from the Nano. I don't think that is the problem, because of I tested my setup in this project:
#include <EtherCard.h>
#include <IPAddress.h>
#include <string.h>

#define LIGHT 6

static byte myip[] = { 192,168,1,3 };
static byte gwip[] = { 10,21,224,1 };
static byte dnsip[] = { 195,98,64,65 };

static byte mymac[] = { 0x70,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[500]; // tcp/ip send and receive buffer

//callback that prints received packets to the serial port
void handler(uint16_t dest_port, uint8_t src_ip[IP_LEN], uint16_t src_port, const char *data, uint16_t len){
  IPAddress src(src_ip[0],src_ip[1],src_ip[2],src_ip[3]);

  Serial.println("Connection from:");
  Serial.print("dest_port: ");
  Serial.println(dest_port);
  Serial.print("src_port: ");
  Serial.println(src_port);
  Serial.print("src_ip: ");
  ether.printIp(src_ip);
  Serial.println();
  Serial.print("data: ");
  Serial.println(data);

  if (strcmp("1", data) == 0) {
    digitalWrite(LIGHT, HIGH);
  }
  else if (strcmp("0", data) == 0) {
    digitalWrite(LIGHT, LOW);
  }
  else {
    Serial.println("Invalid command!");
  }
}

void setup(){
  pinMode(LIGHT, OUTPUT);

  Serial.begin(57600);
  Serial.println(F("\n[backSoon]"));

  // Change 'SS' to your Slave Select pin, if you arn't using the default pin
  if (ether.begin(sizeof Ethernet::buffer, mymac, SS) == 0)
    Serial.println(F("Failed to access Ethernet controller"));
  ether.staticSetup(myip, gwip, dnsip);
  ether.printIp("IP:  ", ether.myip);
  ether.printIp("GW:  ", ether.gwip);
  ether.printIp("DNS: ", ether.dnsip);
  Serial.println();

  //register udpSerialPrint() to port 1234
  ether.udpServerListenOnPort(&handler, 10003);
}

void loop(){
  //this must be called for ethercard functions to work.
  ether.packetLoop(ether.packetReceive());
}

I can't even light the pin from remote (VPS) machine. I use scapy to send 0 or 1 to my setup from VPS server and it's working.

What should I do to diagnose network problem? It's like dgrams don't get to my app server.

what program is running on the PC
if I run this UDP chat program on a Nano with a ENC28j60

// UDP chat program using  ENC28J60  tested on UNO and Nano
// **** change IP addresses and ports to suit requirements *****

#include <EthernetENC.h>  // for  ENC28J60
#include <EthernetUdp.h>  // for UDP

// *****   IP of this machine and remote machine *********
IPAddress localIP;      // these will be read from the keyboard
IPAddress remoteIP;

// Enter a MAC address
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

unsigned int localPort = 10000;   // local port to listen on
unsigned int remotePort = 10000;  // remote port to transmiit too

// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial)
    ;
  Serial.println("\nEthernet UDP chat program");
  // Check for Ethernet hardware present

  // You can use Ethernet.init(pin) to configure the CS pin
  Ethernet.init(10);  // Most Arduino shields
                      //Ethernet.init(5);   // MKR ETH Shield
                      //Ethernet.init(0);   // Teensy 2.0
                      //Ethernet.init(20);  // Teensy++ 2.0
                      //Ethernet.init(15);  // ESP8266 with Adafruit FeatherWing Ethernet
                      //Ethernet.init(33);  // ESP32 with Adafruit FeatherWing Ethernet
  localIP = getIPaddress("\nenter local IP address (e.g. 192.168.1.176)? ");
  Serial.print("\nRemote ");
  //displayMACaddress(mac);
  mac[5] = localIP[3];  // change default MAC address
  displayMACaddress(mac);
  // start the Ethernet
  Ethernet.begin(mac, localIP);
  if (Ethernet.hardwareStatus() == EthernetNoHardware) {
    Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    while (true) delay(1);  // do nothing, no point running without Ethernet hardware
  }
  if (Ethernet.linkStatus() == LinkOFF) {
    Serial.println("Ethernet cable is not connected.");
  }
  Udp.begin(localPort);  // start UDP
  Serial.print("Ethernet UDP started ");
  displayIPaddress(localIP, localPort);
  // get remote IP address
  remoteIP = getIPaddress("\nenter remote IP address (e.g. 192.168.1.176)? ");
  Serial.print("\nRemote ");
  displayIPaddress(remoteIP, remotePort);
}

void loop() {
  Udp.begin(localPort);
  // if Serial text entered transmit as a datagram
  if (Serial.available()) {
    Udp.begin(localPort);
    char text[20] = { 0 };
    Serial.readBytesUntil('\n', text, 24);
    Serial.print("Transmitting to ");
    displayIPaddress(remoteIP, remotePort);
    Serial.println(text);
    Udp.beginPacket(remoteIP, remotePort);  // transmit datagram
    Udp.print(text);
    Udp.endPacket();
  }
  // 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 ");
    displayIPaddress(Udp.remoteIP(), Udp.remotePort());
    // read the packet into packetBuffer
    char packetBuffer[100] = { 0 };      // buffer to hold incoming packet,
    Udp.read(packetBuffer, packetSize);  //UDP_TX_PACKET_MAX_SIZE);     // receive datagram
    Serial.print("Contents: ");
    Serial.println(packetBuffer);
    // if (strcmp(packetBuffer, "OK") != 0) {
      
    // send a reply to the IP address and port that sent us the packet we received
    //   Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
    // Udp.write("OK");
    //  Udp.endPacket();
    //}
  }
  delay(10);
}

// read IP address from keyboard and check it
IPAddress getIPaddress(const char* prompt) {
  IPAddress ip;
  while (1) {  // read  IP (end with new line)
    Serial.print(prompt);
    while (Serial.available() == 0) delay(10);
    char text[40] = { 0 };
    Serial.readBytesUntil('\n', (char*)text, 40);
    //Serial.println(text);
    if (ip.fromString(text)) break;  // if IP OK break while
    Serial.println("\ninvalid IP try again");
  }
  return ip;
}


// print IPAdress and port
void displayIPaddress(const IPAddress address, unsigned int port) {
  Serial.print(" IP ");
  for (int i = 0; i < 4; i++) {
    Serial.print(address[i], DEC);
    if (i < 3) Serial.print(".");
  }
  Serial.print(" port ");
  Serial.println(port);
}

void displayMACaddress(byte address[]) {
  Serial.print("MAC address ");
  for (int i = 0; i < 6; i++) {
    Serial.print("0x");
    Serial.print(address[i], HEX);
    if (i < 5) Serial.print(".");
  }
  Serial.println();
}

and this Java UDPchat program on a PC

// UDPchat.java - simple peer-to-peer chat program using UDP
//           - given remote IP address can send strings using UDP datagrams 
//           - will also wait for datagrams and display contents
// remote IP and port are specified via command line - default IP is 127.0.0.1 (i.e. localhost) and port is 1000  
//
// e.g. to send datagrams to IP 146.227.59.130 port 1006
// java chat 146.227.59.130 1006

import java.io.*;
import java.util.*;
import java.net.*;

public class UDPchat extends Thread
{
   private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   int port=10000;//999;//10001;// 100006                             // port to send/receive datagrams on
   String remoteIPaddress= "192.168.1.176";//"169.254.144.20";//("192.168.1.8");//127.0.0.1");      // IP to send datagrams

   // constructor, parameter is command line parameters
   public UDPchat(String args[]) throws Exception
    {
    // get remote IP address and port from command line parameters
    if (args.length > 0)    remoteIPaddress =  (args[0]);           // get IPaddress
    if (args.length > 1)    port = Integer.parseInt(args[1]);        // get port number
    System.out.println("chat program: IP address " + InetAddress.getLocalHost().toString() + " port " + port );
    
    start();        // start thread to receive and display datagrams

    // loop waiting for keyboard input, send datagram to remote IP                
    while(true)
      try
        {
        String s = in.readLine();                       // read a String
        System.out.println("Sending to " + remoteIPaddress + " socket " + port + " data: " + s);
        byte[] data = s.getBytes();                                     // convert to byte array
        DatagramSocket theSocket = new DatagramSocket();                // create datagram socket and the datagram
        DatagramPacket   theOutput = new DatagramPacket(data, data.length, InetAddress.getByName(remoteIPaddress), port);
        theSocket.send(theOutput);                                      // and send the datagram
       }
      catch (Exception e) {System.out.println("Eroor sending datagram " + e);}
    }

   // thread run method, receives datagram and display contents as a string
   public void run()                
        {
          try
              {
              // open DatagramSocket to receive 
              DatagramSocket ds = new DatagramSocket(port);
              // loop forever reading datagrams from the DatagramSocket
              while (true)
                 {
                 byte[] buffer = new byte[65507];                       // array to put datagrams in
                 DatagramPacket dp = new DatagramPacket(buffer, buffer.length); // DatagramPacket to hold the datagram
                 ds.receive(dp);                                     // wait for next datagram
                 String s = new String(dp.getData(),0,dp.getLength());        // get contenets as a String
                 System.out.println("UDP datagram length " + s.length()+ "  from IP " + dp.getAddress() + " received: " + s );
                 }
              }
          catch (SocketException se) {System.err.println("chat error " + se); }
          catch (IOException se) {System.err.println("chat error " + se);}
          System.exit(1);                                                       // exit on error
        }


public static void main(String args[]) throws Exception
{
   UDPchat c=new UDPchat(args);
}

}

the PC displays

F:\UDPchat>javac UDPchat.java

F:\UDPchat>java UDPchat
chat program: IP address BB-DELL2/192.168.1.68 port 10000
UDP datagram length 15  from IP /192.168.1.176 received: hello from nano
UDP datagram length 16  from IP /192.168.1.176 received: test 2 from nano
heloo from Pc
Sending to 192.168.1.176 socket 10000 data: heloo from Pc
test2 from pc 1234567890
Sending to 192.168.1.176 socket 10000 data: test2 from pc 1234567890
UDP datagram length 24  from IP /192.168.1.176 received: test3 from nano 12345678
UDP datagram length 2  from IP /192.168.1.176 received: 90

and the Nano displays

11:52:38.636 -> Ethernet UDP chat program
11:52:38.636 -> 
11:57:57.047 -> enter local IP address (e.g. 192.168.1.176)? 
11:58:22.439 -> Remote MAC address 0xDE.0xAD.0xBE.0xEF.0xFE.0xB0
11:58:22.503 -> Ethernet cable is not connected.
11:58:22.503 -> Ethernet UDP started  IP 192.168.1.176 port 10000
11:58:22.503 -> 
11:58:22.503 -> enter remote IP address (e.g. 192.168.1.176)? 
11:58:47.769 -> Remote  IP 192.168.1.68 port 10000
11:58:58.364 -> Transmitting to  IP 192.168.1.68 port 10000
11:58:58.398 -> hello from nano
11:59:11.072 -> Transmitting to  IP 192.168.1.68 port 10000
11:59:11.072 -> test 2 from nano
11:59:28.712 -> Received packet of size 13
11:59:28.712 -> From  IP 192.168.1.68 port 62709
11:59:28.746 -> Contents: heloo from Pc
11:59:42.652 -> Received packet of size 24
11:59:42.652 -> From  IP 192.168.1.68 port 64535
11:59:42.652 -> Contents: test2 from pc 1234567890
11:59:56.328 -> Transmitting to  IP 192.168.1.68 port 10000
11:59:56.328 -> test3 from nano 12345678
11:59:57.334 -> Transmitting to  IP 192.168.1.68 port 10000
11:59:57.334 -> 90

I run simple python udp server:

import socket
localIP     = "0.0.0.0"
localPort   = 10002
bufferSize  = 1024
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")
while(True):
    bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
    message = bytesAddressPair[0]
    address = bytesAddressPair[1]
    clientMsg = "Message from Client:{}".format(message)
    clientIP  = "Client IP Address:{}".format(address)
    print(clientMsg)
    print(clientIP)

Strange. I used my own configuration, but I recieved "Ethernet cable is not connected." Maybe thats why my arduino not original?

ran your python server changed port to 10000 to suit nano code of post 5
works OK
nano serial monitor

20:17:21.782 -> Ethernet UDP chat program
20:17:21.782 -> 
20:17:21.782 -> enter local IP address (e.g. 192.168.1.176)? 
20:17:38.403 -> Remote MAC address 0xDE.0xAD.0xBE.0xEF.0xFE.0xB0
20:17:38.435 -> Ethernet cable is not connected.
20:17:38.468 -> Ethernet UDP started  IP 192.168.1.176 port 10000
20:17:38.468 -> 
20:17:38.468 -> enter remote IP address (e.g. 192.168.1.176)? 
20:17:55.789 -> Remote  IP 192.168.1.68 port 10000
20:18:29.886 -> Transmitting to  IP 192.168.1.68 port 10000
20:18:29.886 -> hello
20:18:44.937 -> Transmitting to  IP 192.168.1.68 port 10000
20:18:44.937 -> hello from nano
20:18:57.745 -> Transmitting to  IP 192.168.1.68 port 10000
20:18:57.745 -> test 2 froim nano

python monitor displays

Python 3.11.9 (tags/v3.11.9:de54cf5, Apr  2 2024, 10:12:12) [MSC v.1938 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.

= RESTART: F:/Programming/python/UDP_server_2.py
UDP server up and listening
Message from Client:b'hello'
Client IP Address:('192.168.1.176', 10000)
Message from Client:b'hello from nano'
Client IP Address:('192.168.1.176', 10000)
Message from Client:b'test 2 froim nano'
Client IP Address:('192.168.1.176', 10000)

I am using a Nano ENC28J60 Ethernet Shield similar to the one in photo in post 3

I guess, it is something with board or shield. I only receive message about no cable (

There is something insane. For me, it worked to use makeUdpReply to send back udps. But I still struggling to send something without replying it? Could you believe in that? What should I do?

I just need to know, how simply send udps. I heard something, that OS can block some udps? Maybe this is the reason?

UDP is a connectionless protocol - must be the program which is the problem
the Nano/Java UDP chat programs of post 5 can transmit/receive at any time

OS firewall will block TCP/UDP ports - you need to open specific ports to receive

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.