SimpleSocket 1.0 examples

Dependencies:   EthernetNetIf SimpleSocket 1.0 mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers findbuddy.cpp Source File

findbuddy.cpp

00001 #include "EthernetNetIf.h"
00002 #include "SimpleSocket.h"
00003 
00004 void findbuddy() {
00005     EthernetNetIf eth;
00006     eth.setup();
00007    
00008     IpAddr myIP = eth.getIp();
00009     DatagramSocket datagram(myIP, 7777);
00010 
00011     Host buddy;
00012     for (int i = myIP[3] + 1;; i = (i - myIP[3] + 260) % 10 + myIP[3] + 1) {
00013         printf("sending message to %d.%d.%d.%d\n", myIP[0], myIP[1], myIP[2], i);
00014         datagram.printf("Hello World\n");
00015         datagram.send(IpAddr(myIP[0], myIP[1], myIP[2], i), 7777);
00016         // this will not reach target during the first round,
00017         // and in order to receive successfully,
00018         // timeout must be at least 4 seconds (default = 5.0 seconds)
00019         if (datagram.receive(&buddy, 4) > 0) {
00020             IpAddr ip = buddy.getIp();
00021             char buf[80] = {};
00022             int len = datagram.read(buf, sizeof(buf) - 1);
00023             printf("received from %d.%d.%d.%d: %s", ip[0],ip[1], ip[2], ip[3], buf);
00024             break;
00025         }
00026     }
00027 
00028     for (int i = 0; i < 2; i++) {
00029         datagram.printf("There you are!\n");
00030         datagram.send(buddy.getIp(), 7777);
00031 
00032         if (datagram.receive() > 0) {
00033             char buf[80] = {};
00034             int len = datagram.read(buf, sizeof(buf) - 1);
00035             printf("received: %s", buf);
00036         }
00037     }
00038 }