Simple TCP/IP Server using the UIPEthernet library for ENC28J60 Ethernet boards.

Dependencies:   UIPEthernet

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*
00002  * Simple TcpServer using the UIPEthernet library for ENC28J60 Ethernet boards.
00003  *
00004  */
00005 #include "mbed.h"
00006 #include "UipEthernet.h"
00007 #include "TcpServer.h"
00008 #include "TcpClient.h"
00009 
00010 #define IP      "192.168.1.35"
00011 #define GATEWAY "192.168.1.1"
00012 #define NETMASK "255.255.255.0"
00013 #define PORT    80
00014 
00015 const uint8_t   MAC[6] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 };
00016 UipEthernet     net(MAC, D11, D12, D13, D10);   // mac, mosi, miso, sck, cs
00017 TcpServer       server;                         // Ethernet server
00018 TcpClient*      client;
00019 uint8_t         recvData[1024];
00020 const char      sendData[] = "Data received OK";
00021 
00022 /**
00023  * @brief
00024  * @note
00025  * @param
00026  * @retval
00027  */
00028 int main(void)
00029 {
00030     printf("Starting ...\r\n");
00031 
00032     //net.set_network(IP, NETMASK, GATEWAY);  // include this to use static IP address
00033     net.connect();
00034 
00035     // Show the network address
00036     const char*     ip = net.get_ip_address();
00037     const char*     netmask = net.get_netmask();
00038     const char*     gateway = net.get_gateway();
00039 
00040     printf("IP address: %s\r\n", ip ? ip : "None");
00041     printf("Netmask: %s\r\n", netmask ? netmask : "None");
00042     printf("Gateway: %s\r\n\r\n", gateway ? gateway : "None");
00043 
00044     /* Open the server on ethernet stack */
00045     server.open(&net);
00046 
00047     /* Bind the HTTP port (TCP 80) to the server */
00048     server.bind(PORT);
00049 
00050     /* Can handle 4 simultaneous connections */
00051     server.listen(4);
00052 
00053     while (true) {
00054         client = server.accept();
00055 
00056         if (client) {
00057             size_t  recvLen;
00058 
00059             printf("\r\n----------------------------------\r\n");
00060             printf("Client with IP address %s connected.\n\r", client->getpeername());
00061             if ((recvLen = client->available()) > 0) {
00062                 printf("%d bytes received:\r\n", recvLen);
00063                 client->recv(recvData, recvLen);
00064                 for (int i = 0; i < recvLen; i++)
00065                     printf(" 0x%.2X", recvData[i]);
00066                 printf("\r\n");
00067                 client->send((uint8_t*)sendData, strlen(sendData));
00068                 printf("%s\r\n", sendData);
00069             }
00070 
00071             printf("Client with IP address %s disconnected.\r\n", client->getpeername());
00072             client->close();
00073         }
00074     }
00075 }