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:
- 2017-06-30
- Revision:
- 6:c5eb31c60c8f
- Parent:
- 5:068f4c368ab0
- Child:
- 7:f6058bcaa614
File content as of revision 6:c5eb31c60c8f:
/* * 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" #include "UIPServer.h" #include "UIPClient.h" #define DHCP 1 // if you'd like to use static IP address comment out this line // MAC address must be unique within the connected network. Modify as appropriate. const uint8_t MY_MAC[6] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05 }; const uint16_t MY_PORT = 80; // for HTTP connection Serial pc(USBTX, USBRX); #if defined(TARGET_LPC1768) UIPEthernet uIPEthernet(p11, p12, p13, p8); // mosi, miso, sck, cs #elif defined(TARGET_NUCLEO_F103RB) || defined(TARGET_NUCLEO_L152RE) || defined(TARGET_NUCLEO_F030R8) \ || defined(TARGET_NUCLEO_F401RE) || defined(TARGET_NUCLEO_F302R8) || defined(TARGET_NUCLEO_L053R8) \ || defined(TARGET_NUCLEO_F411RE) || defined(TARGET_NUCLEO_F334R8) || defined(TARGET_NUCLEO_F072RB) \ || defined(TARGET_NUCLEO_F091RC) || defined(TARGET_NUCLEO_F303RE) || defined(TARGET_NUCLEO_F070RB) \ || defined(TARGET_KL25Z ) || defined(TARGET_KL46Z) || defined(TARGET_K64F) || defined(TARGET_KL05Z) \ || defined(TARGET_K20D50M) || defined(TARGET_K22F) \ || defined(TARGET_NRF51822) \ || defined(TARGET_RZ_A1H) UIPEthernet uIPEthernet(D11, D12, D13, D10); // mosi, miso, sck, cs #endif EthernetServer myServer = EthernetServer(MY_PORT); int main(void) { #if defined(DHCP) pc.printf("Searching for DHCP server..\r\n"); if (uIPEthernet.begin(MY_MAC) != 1) { pc.printf("No DHCP server found.\r\n"); pc.printf("Exiting application.\r\n"); return 0; } pc.printf("DHCP server found.\r\n"); #else // IP address must be unique and compatible with your network. const IPAddress MY_IP(192, 168, 1, 181); // Change as appropriate. uIPEthernet.begin(MY_MAC, MY_IP); #endif pc.printf("Local IP = %s\r\n", uIPEthernet.localIP().toString()); myServer.begin(); while (1) { char echoHeader[256]; EthernetClient client = myServer.available(); if (client) { size_t size = client.available(); if (size > 0) { char* buf = (char*)malloc(size); size = client.read((uint8_t*)buf, size); if (buf[0] == 'G' && buf[1] == 'E' && buf[2] == 'T') { pc.printf("GET request received:\n\r"); pc.printf(buf); sprintf ( echoHeader, "HTTP/1.1 200 OK\r\nContent-Length: %d\r\nContent-Type: text\r\nConnection: About to close\r\n\r\n", size ); client.write((uint8_t*)echoHeader, strlen(echoHeader)); client.write((uint8_t*)buf, size); pc.printf("Echo done.\r\n"); } free(buf); } } } }