DhcpChatServer.ino 2.4 KB

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