Simple UDP Server using the UIPEthernet library for ENC28J60 Ethernet boards.

Dependencies:   UIPEthernet

Revision:
0:8823772081cb
Child:
1:29bb0a32f61d
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Fri Jun 30 20:42:13 2017 +0000
@@ -0,0 +1,81 @@
+#include "mbed.h"
+#include "UIPEthernet.h"
+#include "UIPUdp.h"
+
+// MAC address must be unique within the connected network. Modify as appropriate.
+const uint8_t    MY_MAC[6] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
+// IP address must be unique and compatible with your network.
+const IPAddress  MY_IP(192, 168, 1, 181);
+const uint16_t   MY_PORT = 7;
+
+Serial           pc(USBTX, USBRX);
+UIPEthernet      uIPEthernet(D11, D12, D13, D10);    // mosi, miso, sck, cs
+UIPUDP           udp;
+
+/**
+ * @brief
+ * @note
+ * @param
+ * @retval
+ */
+int main(void) {
+    uIPEthernet.begin(MY_MAC, MY_IP);
+    IPAddress   localIP = uIPEthernet.localIP();
+    pc.printf("Local IP = %s\r\n", localIP.toString());
+    pc.printf("Initialization ");
+    if(udp.begin(MY_PORT))
+        pc.printf("succeeded.\r\n");
+    else
+        pc.printf("failed.\r\n");
+
+    while(1) {
+        int size = udp.parsePacket();
+        if(size > 0) {
+            do {
+                char*   msg = (char*)malloc(size + 1);
+                int     len = udp.read(msg, size + 1);
+                msg[len] = 0;
+            } while((size = udp.available()) > 0);
+
+            //finish reading this packet:
+            udp.flush();
+
+            int success;
+            do {
+                //send new packet back to ip/port of client. This also
+                //configures the current connection to ignore packets from
+                //other clients!
+                success = udp.beginPacket(udp.remoteIP(), udp.remotePort());
+                if(success)
+                    pc.printf("beginPacket: succeeded%\r\n");
+                else
+                    pc.printf("beginPacket: failed%\r\n");
+
+                //beginPacket fails if remote ethaddr is unknown. In this case an
+                //arp-request is send out first and beginPacket succeeds as soon
+                //the arp-response is received.
+            } while(!success);
+
+            char*   message = "Hello World from mbed";
+            success = udp.write((uint8_t*)message, strlen(message));
+
+            if(success)
+                pc.printf("bytes written: %d\r\n", success);
+
+            success = udp.endPacket();
+
+            if(success)
+                pc.printf("endPacket: succeeded%\r\n");
+            else
+                pc.printf("endPacket: failed%\r\n");
+
+            udp.stop();
+
+            //restart with new connection to receive packets from other clients
+            if(udp.begin(MY_PORT))
+                pc.printf("restart connection: succeeded%\r\n");
+            else
+                pc.printf("restart connection: failed%\r\n");
+        }
+    }
+}