Skip to content

Instantly share code, notes, and snippets.

@cgundogan
Last active November 25, 2015 16:37
Show Gist options
  • Save cgundogan/25bc8e16d506460d4d98 to your computer and use it in GitHub Desktop.
Save cgundogan/25bc8e16d506460d4d98 to your computer and use it in GitHub Desktop.
simple udp server
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFSIZE 1024
void error(char *msg) {
perror(msg);
exit(1);
}
int main(int argc, char **argv) {
int sockfd, clientlen, optval, n;
struct sockaddr_in clientaddr;
struct hostent *hostp;
char buf[BUFSIZE], *hostaddrp;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) error("ERROR opening socket");
optval = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int));
clientlen = sizeof(clientaddr);
while (1) {
bzero(buf, BUFSIZE);
/* uncomment from here */
clientaddr.sin_family = AF_INET;
clientaddr.sin_port = htons(6655);
n = sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *) &clientaddr, clientlen);
if (n < 0) error("ERROR in sendto");
/* to here */
n = recvfrom(sockfd, buf, BUFSIZE, 0, (struct sockaddr *) &clientaddr, &clientlen);
if (n < 0) error("ERROR in recvfrom");
hostp = gethostbyaddr((const char *)&clientaddr.sin_addr.s_addr, sizeof(clientaddr.sin_addr.s_addr), AF_INET);
if (hostp == NULL) error("ERROR on gethostbyaddr");
hostaddrp = inet_ntoa(clientaddr.sin_addr);
if (hostaddrp == NULL) error("ERROR on inet_ntoa\n");
printf("server received datagram from %s (%s)\n", hostp->h_name, hostaddrp);
printf("server received %d/%d bytes: %s\n", strlen(buf), n, buf);
n = sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *) &clientaddr, clientlen);
if (n < 0) error("ERROR in sendto");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment