A simple HTTP server echoing received requests. Ethernet connection is over an ENC28J60 board. Usage: Type the server's IP address into you web browser and hit <ENTER>.
main.cpp
- Committer:
- hudakz
- Date:
- 2020-07-23
- Revision:
- 11:754a62936db7
- Parent:
- 10:ae9303c25085
File content as of revision 11:754a62936db7:
/* * In this example the HTTP request (text) received from a browser is echoed (sent back) to the browser. * Ethernet connection is via an ENC28J60 Ethernet board driven by the UIPEthernet library */ #include "mbed.h" #include "UipEthernet.h" #define IP "192.168.1.35" #define GATEWAY "192.168.1.1" #define NETMASK "255.255.255.0" #define PORT 80 const uint8_t MAC[6] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; UipEthernet net(MAC, D11, D12, D13, D10); // mac, mosi, miso, sck, cs //UipEthernet net(MAC, PA_7, PA_6, PA_5, PB_6); // mac, mosi, miso, sck, cs TcpServer server; // Ethernet server TcpClient* client; char receiveBuf[1024]; char echoHeader[256]; /** * @brief * @note * @param * @retval */ int main(void) { printf("Starting ...\r\n"); //net.set_network(IP, NETMASK, GATEWAY); // include this to use static IP address net.connect(); // 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"); printf("------------------------------------------------------\r\n"); printf("Usage: Type %s into your web browser and hit ENTER\r\n", net.get_ip_address()); printf("------------------------------------------------------\r\n"); /* Open the server on ethernet stack */ server.open(&net); /* Bind the HTTP port (TCP 80) to the server */ server.bind(PORT); /* Can handle 5 simultaneous connections */ server.listen(5); while (1) { client = server.accept(); if (client) { size_t receiveLen = client->recv((uint8_t*)receiveBuf, client->available()); if (receiveBuf[0] == 'G' && receiveBuf[1] == 'E' && receiveBuf[2] == 'T') { printf("\r\n-------------------------------------------------------\r\n"); printf("GET request received from a client with IP address %s\n\r", client->getpeername()); printf("%s\r\n", receiveBuf); sprintf ( echoHeader, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\nContent-Type: text\r\nConnection: About to close\r\n\r\n", receiveLen ); client->send((uint8_t*)echoHeader, strlen(echoHeader)); client->send((uint8_t*)receiveBuf, receiveLen); printf("Echo done.\r\n"); } client->close(); } } }