Stanly Chen
/
K64-UDP-Socket
K64F, use static IP, UDP broadcast
main.cpp
- Committer:
- stanly88
- Date:
- 2019-04-02
- Revision:
- 1:8bbcb6a6ca18
- Parent:
- 0:cf516d904427
File content as of revision 1:8bbcb6a6ca18:
#include "mbed.h" #include "EthernetInterface.h" // Network interface EthernetInterface net; // Time protocol implementation : Address: time.nist.gov UDPPort: 37 typedef struct { uint32_t secs; // Transmit Time-stamp seconds. }ntp_packet; int main() { // Bring up the ethernet interface printf("UDP Socket example\n"); if( NSAPI_ERROR_OK != net.set_network("192.168.0.119",//Static IP "255.255.255.0", //NetMask "192.168.0.1") )// gateway ) { printf("Static IP setting Error\n"); } if(0 != net.connect()) { printf("Error connecting\n"); return -1; } // Show the network address const char *ip = net.get_ip_address(); printf("IP address is: %s\n", ip ? ip : "No IP"); UDPSocket sock(&net); SocketAddress sockAddr; /* char out_buffer[] = "time"; if(0 > sock.sendto("time.nist.gov", 37, out_buffer, sizeof(out_buffer))) { printf("Error sending data\n"); return -1; } ntp_packet in_data; int n = sock.recvfrom(&sockAddr, &in_data, sizeof(ntp_packet)); in_data.secs = ntohl( in_data.secs ) - 2208988800; // 1900-1970 printf("Time Received %lu seconds since 1/01/1900 00:00 GMT\n", (uint32_t)in_data.secs); printf("Time = %s", ctime(( const time_t* )&in_data.secs)); printf("Time Server Address: %s Port: %d\n\r", sockAddr.get_ip_address(), sockAddr.get_port()); // Close the socket and bring down the network interface sock.close(); net.disconnect(); */ char out_buffer[40]; int sendCnt = 0; while(1) { sprintf(out_buffer,"Tx:%d\r\n", ++sendCnt); if(0 > sock.sendto("192.168.0.255", 2000, out_buffer, strlen(out_buffer))) { printf("Error sending data\n"); break; } printf(out_buffer); wait(0.5); } sock.close(); net.disconnect(); return 0; }