For a project I was working on, I needed to get to understand UDP communication to automate a certain process. The code below runs on the server which can be tested using a simple command line on a linux terminal:
ncat -vv localhost 8887 -u
What is typed in the terminal is echoed back. Obviously UDP has advantages and disadvantages. In the case for what I was using it for, it was a perfect solution.
#include#include #include #include #include #define BUFLEN 200 #define PORT 8887 void die(char *s) { perror(s); exit(1); } int main() { printf("!!!Hello World!!!\n"); struct sockaddr_in si_me, si_other; int s; unsigned int slen = sizeof(si_other); size_t recv_len; char buf[BUFLEN + 1]; if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { die("socket"); } memset((char*)&si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(s,(struct sockaddr*)&si_me,sizeof(si_me)) == -1) { die("bind"); } while(1) { printf("Waiting for data...\n"); if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr*)&si_other, &slen)) == -1) { die("recvfrom()"); } buf[recv_len] = 0; printf("Packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); printf("Data: %s\n", buf); if (sendto(s, buf, recv_len, 0, (struct sockaddr*)&si_other, slen) == -1) { die("sendto()"); } } close(s); return 0; }
UPDATE (4th May 2016):
I needed a way of connecting new devices to a network that would sniff out UDP traffic to locate the server to which it would then connect to so that they could be set up via another interface without actually needing any interaction with the device itself. The network itself was closed and so new devices wouldn’t have the local time set either. The UDP broadcast would also send the time too.