dhilst

UDP, Server and Client examples

/*
* udpserver.c
*
* UDP Server example
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define pexit(s) ({perror(s); exit(EXIT_FAILURE);})

int main(int argc, char **argv)
{
#define BUFLEN 1000
char buf[BUFLEN];
int sock, error, clilen, bytes;
struct sockaddr_in srv, cli;

if (argc < 2) {
printf("Usage: %s PORT\n", argv[0]);
exit(EXIT_FAILURE);
}

sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
pexit("socket");


memset(&srv, 0, sizeof(srv));
srv.sin_family = AF_INET;
srv.sin_port = htons(atoi(argv[1]));
srv.sin_addr.s_addr = htonl(INADDR_ANY);

error = bind(sock, (struct sockaddr *)&srv, sizeof(srv));

for (;;) {
clilen = sizeof(cli);
bytes = recvfrom(sock, buf, BUFLEN, 0, (struct sockaddr *)&cli,
&clilen);
if (bytes == -1)
pexit("recvfrom");

printf("received data from %s\n",
inet_ntoa(cli.sin_addr.s_addr));
buf[bytes] = '\0';
printf(">>%s<<\n", buf);
}
return 0;
}


/*
* udpclient.c
*
* UDP client example
*/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define pexit(s) ({perror(s); exit(EXIT_FAILURE);})

int main(int argc, char **argv)
{
int sock, error, srvlen, bytes;
struct sockaddr_in srv;

if (argc <= 2) {
printf("Usage: %s IP PORT\n", argv[0]);
exit(EXIT_FAILURE);
}

sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1)
pexit("socket");


memset(&srv, 0, sizeof(srv));
srv.sin_family = AF_INET;
srv.sin_port = htons(atoi(argv[2]));
srv.sin_addr.s_addr = inet_addr(argv[1]);

bytes = sendto(sock, "Hello World", strlen("Hello World"), 0,
(struct sockaddr *)&srv, sizeof(srv));
if (bytes == -1)
pexit("sendto");

close(sock);

return 0;
}