examples for SimpleSocket/EthernetInterface
Dependencies: EthernetInterface SimpleSocket mbed-rtos mbed
Diff: examples/findbuddy.cpp
- Revision:
- 0:6dc3cfd058c6
diff -r 000000000000 -r 6dc3cfd058c6 examples/findbuddy.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/findbuddy.cpp Mon Feb 04 09:29:18 2013 +0000 @@ -0,0 +1,40 @@ +#include "SimpleSocket.h" + +void findbuddy() +{ + int myIP[4]; + sscanf(EthernetInterface::getIPAddress(), "%d.%d.%d.%d", myIP, myIP + 1, myIP + 2, myIP + 3); + + DatagramSocket datagram(7777); + + char buddy[32] = {}; + int port; + for (int i = myIP[3] + 1;; i = (i - myIP[3] + 260) % 10 + myIP[3] + 1) { + sprintf(buddy, "%d.%d.%d.%d", myIP[0], myIP[1], myIP[2], i); + printf("sending message to %s\n", buddy); + datagram.printf("Hello World\n"); + + datagram.send(buddy, 7777); + // this will not reach target during the first round, + // and in order to receive successfully, + // timeout must be at least 4 seconds (default = 5.0 seconds) + datagram.setTimeout(4.0); + if (datagram.receive(buddy, &port) > 0) { + char buf[80] = {}; + int len = datagram.read(buf, sizeof(buf) - 1); + printf("received from %s: %s", buddy, buf); + break; + } + } + + for (int i = 0; i < 2; i++) { + datagram.printf("There you are!\n"); + datagram.send(buddy, 7777); + + if (datagram.receive() > 0) { + char buf[80] = {}; + int len = datagram.read(buf, sizeof(buf) - 1); + printf("received: %s", buf); + } + } +} \ No newline at end of file