UDP Echo Client example

Dependencies:   EthernetInterface mbed-rtos mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "EthernetInterface.h"
00003  
00004 const char* ECHO_SERVER_ADDRESS = "192.168.2.2";
00005 const int ECHO_SERVER_PORT = 7;
00006  
00007 int main() {
00008     EthernetInterface eth;
00009     eth.init(); //Use DHCP
00010     eth.connect();
00011     printf("\nClient IP Address is %s \n", eth.getIPAddress());
00012     
00013     UDPSocket sock;
00014     sock.init();
00015     
00016     Endpoint echo_server;
00017     echo_server.set_address(ECHO_SERVER_ADDRESS, ECHO_SERVER_PORT);
00018     
00019     char out_buffer[] = "Hello World";
00020     printf("Sending  message '%s' to server (%s)\n",out_buffer,ECHO_SERVER_ADDRESS);
00021     sock.sendTo(echo_server, out_buffer, sizeof(out_buffer));
00022     
00023     char in_buffer[256];
00024     int n = sock.receiveFrom(echo_server, in_buffer, sizeof(in_buffer));
00025     
00026     in_buffer[n] = '\0';
00027     printf("Received message from server: '%s'\n", in_buffer);
00028     
00029     sock.close();
00030     
00031     eth.disconnect();
00032     while(1) {}
00033 }