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

Dependencies:   UIPEthernet

main.cpp

Committer:
hudakz
Date:
2019-09-07
Revision:
3:6a6fe4ef95b9
Parent:
2:c69ad6e71f97

File content as of revision 3:6a6fe4ef95b9:

/*
 * UipEthernet UdpClient example.
 *
 * UipEthernet is a TCP/IP stack that can be used with an enc28j60 based
 * Ethernet-shield.
 *
 * UipEthernet uses the fine uIP stack by Adam Dunkels <adam@sics.se>
 *
 *      -----------------
 *
 * Mbed's UDPSocket example
 * https://os.mbed.com/docs/mbed-os/v5.13/apis/udpsocket.html#udpsocket-example
 * modified by Zoltan Hudak for UIPEthernet
 *
 */
#include "mbed.h"
#include "UipEthernet.h"
 
// MAC address must be unique within the connected network. Modify as appropriate.
const uint8_t   MAC[6] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
UipEthernet     net(MAC, D11, D12, D13, D10);   // mosi, miso, sck, cs
typedef struct
{
    uint32_t    secs;                           // Transmit Time-stamp seconds.
} ntp_packet;
 
/**
 * @brief
 * @note
 * @param
 * @retval
 */
int main(void)
{
    // Bring up the ethernet interface
    printf("UDP Socket example\n");
    if(net.connect() != 0) {
        printf("Error connecting\n");
        return -1;
    }
 
    // Show the network address
    const char*     ip = net.get_ip_address();
    const char*     netmask = net.get_netmask();
    const char*     gateway = net.get_gateway();
 
    printf("IP address: %s\r\n", ip ? ip : "None");
    printf("Netmask: %s\r\n", netmask ? netmask : "None");
    printf("Gateway: %s\r\n\r\n", gateway ? gateway : "None");
 
    UdpSocket       socket(&net);
    SocketAddress   sockAddr;
    char            out_buffer[] = "time";
 
    if (socket.sendto("time.nist.gov", 37, out_buffer, sizeof(out_buffer)) < 0) {
        printf("Error sending data\n");
        return -1;
    }
 
    ntp_packet  in_data;
    socket.recvfrom(&sockAddr, &in_data, sizeof(ntp_packet));
    in_data.secs = ntohl(in_data.secs) - 2208988800;    // 1900-1970
    printf("Time received = %lu seconds since 1/01/1970 00:00 GMT\n", (uint32_t)in_data.secs);
    printf("Time = %s", ctime((const time_t*) &in_data.secs));
    printf("Time Server Address: %s\r\n", sockAddr.get_ip_address());
    printf("Time Server Port: %d\n\r", sockAddr.get_port());
 
    // Close the socket and bring down the network interface
    socket.close();
    net.disconnect();
    return 0;
}