Code:
#include <QNEthernet.h>
using namespace qindesign::network;
constexpr uint16_t kUDPPort = 8888; // Local port for listening
// IP configuration
const IPAddress staticIP(192, 168, 0, 5);
const IPAddress netmask(255, 255, 255, 0);
const IPAddress gatewayIP(192, 168, 0, 1);
EthernetUDP udp;
constexpr int kBufSize = Ethernet.mtu() - 20 - 8; // 20-byte IP, 8-byte UDP header
uint8_t buf[kBufSize];
// Main program setup.
void setup() {
Serial.begin(115200);
while (!Serial && millis() < 4000) {
// Wait for Serial to initialize
}
stdPrint = &Serial; // Make printf work, a QNEthernet feature
// Print the MAC address
uint8_t mac[6];
Ethernet.macAddress(mac);
printf("MAC = %02x:%02x:%02x:%02x:%02x:%02x\n",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
// Start Ethernet
printf("Starting Ethernet with static IP...\n");
if (!Ethernet.begin(staticIP, netmask, gatewayIP)) {
printf("Failed to start Ethernet!\n");
return;
}
Ethernet.setDNSServerIP(gatewayIP);
IPAddress ip = Ethernet.localIP();
printf(" Local IP = %u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);
ip = Ethernet.subnetMask();
printf(" Subnet mask = %u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);
ip = Ethernet.gatewayIP();
printf(" Gateway = %u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);
ip = Ethernet.dnsServerIP();
printf(" DNS = %u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);
// Start listening on the UDP port
udp.begin(kUDPPort);
}
// Main program loop.
void loop() {
int size = udp.parsePacket();
if (size > 0) {
// Print the packet contents
printf("packet[%d]:", size);
// Note: It's possible, due to IP reassembly, to receive a packet
// that's larger than the buffer size
while (size > 0) {
int read = udp.read(buf, std::min(size, kBufSize));
for (int i = 0; i < read; i++) {
printf(" %02x", buf[i]);
}
size -= read;
}
printf("\n");
}
}