UDP server example project for the NetworkAPI library

Dependencies:   EthernetInterface NetworkAPI mbed-rtos mbed

Fork of TCP_Client_Example by Roy van Dam

main.cpp

Committer:
NegativeBlack
Date:
2014-11-15
Revision:
13:33f71f646baa
Parent:
12:f1bed576c7ac

File content as of revision 13:33f71f646baa:

#include "mbed.h"
#include "EthernetInterface.h"
 
#include "NetworkAPI/buffer.hpp"
#include "NetworkAPI/ip/address.hpp"
#include "NetworkAPI/udp/socket.hpp"
 
int
main()
{
    EthernetInterface interface;
    interface.init();
    interface.connect();
    printf("IP Address is %s\n\r", interface.getIPAddress());
   
    network::udp::Socket socket;
    network::Buffer buffer(256);
     
    if (socket.open() < 0) {
        printf("Failed to open UDP Socket\n\r");
        return -1;
    }
     
    if (socket.bind(42) < 0) {
        printf("Failed to bind UDP Socket to port 42\n\r");
    }
     
    while (true) {
        int result = socket.receive(buffer);
         
        switch (result) {
            case -1:
                printf("Failed to read from UDP Socket\n\r");
                return -1;
             
            case 0:
                printf("Nothing received...?\n\r");
                continue;
             
            default:
                printf("Received %d bytes from %s:%d\n\r", result,
                    socket.getRemoteEndpoint().getAddress().toString().c_str(),
                    socket.getRemoteEndpoint().getPort());
                 
                printf("Message: %s\n\r", (char *)buffer.data());
                 
                if (!socket.getRemoteEndpoint().getAddress().isEmpty()) {
                    socket.send(buffer, socket.getRemoteEndpoint());
                }
                continue;
       }
    }
         
    return 0;
}