Skip to content

Commit 4519e4b

Browse files
committed
Added DHCP-based chat server example
1 parent ceddbf9 commit 4519e4b

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/*
2+
DHCP Chat Server
3+
4+
A simple server that distributes any incoming messages to all
5+
connected clients. To use telnet to your device's IP address and type.
6+
You can see the client's input in the serial monitor as well.
7+
Using an Arduino Wiznet Ethernet shield.
8+
9+
THis version attempts to get an IP address using DHCP
10+
11+
Circuit:
12+
* Ethernet shield attached to pins 10, 11, 12, 13
13+
14+
created 21 May 2011
15+
by Tom Igoe
16+
Based on ChatServer example by David A. Mellis
17+
18+
*/
19+
20+
#include <SPI.h>
21+
#include <Ethernet.h>
22+
23+
// Enter a MAC address and IP address for your controller below.
24+
// The IP address will be dependent on your local network.
25+
// gateway and subnet are optional:
26+
byte mac[] = {
27+
0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
28+
IPAddress ip(192,168,1, 177);
29+
IPAddress gateway(192,168,1, 1);
30+
IPAddress subnet(255, 255, 0, 0);
31+
32+
// telnet defaults to port 23
33+
Server server(23);
34+
boolean gotAMessage = false; // whether or not you got a message from the client yet
35+
36+
void setup() {
37+
// open the serial port
38+
Serial.begin(9600);
39+
// start the Ethernet connection:
40+
Serial.println("Trying to get an IP address using DHCP");
41+
if (Ethernet.begin(mac) == 0) {
42+
Serial.println("Failed to configure Ethernet using DHCP");
43+
// initialize the ethernet device not using DHCP:
44+
Ethernet.begin(mac, ip, gateway, subnet);
45+
}
46+
// print your local IP address:
47+
Serial.print("My IP address: ");
48+
ip = Ethernet.localIP();
49+
for (byte thisByte = 0; thisByte < 4; thisByte++) {
50+
// print the value of each byte of the IP address:
51+
Serial.print(ip[thisByte], DEC);
52+
Serial.print(".");
53+
}
54+
Serial.println();
55+
// start listening for clients
56+
server.begin();
57+
58+
}
59+
60+
void loop() {
61+
// wait for a new client:
62+
Client client = server.available();
63+
64+
// when the client sends the first byte, say hello:
65+
if (client) {
66+
if (!gotAMessage) {
67+
Serial.println("We have a new client");
68+
client.println("Hello, client!");
69+
gotAMessage = true;
70+
}
71+
72+
// read the bytes incoming from the client:
73+
char thisChar = client.read();
74+
// echo the bytes back to the client:
75+
server.write(thisChar);
76+
// echo the bytes to the server as well:
77+
Serial.print(thisChar);
78+
}
79+
}
80+

0 commit comments

Comments
 (0)