aboutsummaryrefslogtreecommitdiff
path: root/libraries/Ethernet/examples/echo_server/echo_server.pde
blob: e16dcb9b3b759f03bd999fbd08e3de73a2639abd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
 * Echo Server
 *
 * Echoes back the headers of the web request.  Good for
 * learning how the HTTP protocol works.
 */

#include <Ethernet.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 10, 0, 0, 177 };

Server server(80);

void setup()
{
  Client client(255);
  Ethernet.begin(mac, ip);
  Serial.begin(9600);
  server.begin();
}

void loop()
{
  char buf[512];
  int i = 0;
  Client client = server.available();
  if (client) {
    boolean previous_is_newline = false;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n' && previous_is_newline) {
          buf[i] = 0;
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();
          client.println("<pre>");
          client.println(buf);
          client.println("</pre>");
          break;
        }
        if (i < 511)
          buf[i++] = c;
        if (c == '\n')
          previous_is_newline = true;
        else if (c != '\r')
          previous_is_newline = false;
      }
    }
    client.stop();
  }
}