/* This program creates a datagram server process in the internet domain. it listens on port 51717. On solaris, compile like this gcc -g -Wall server.udp.c -lnsl -lsocket */ #include #include #include #include #include #include #include #define BUFSIZE 1024 void error(char *); int main() { int sock, length, fromlen, n; struct sockaddr_in server; struct sockaddr_in from; char buf[BUFSIZE]; sock=socket(AF_INET, SOCK_DGRAM, 0); if (sock < 0) error("Opening socket"); length = sizeof(server); bzero(&server,length); server.sin_family=AF_INET; server.sin_addr.s_addr=INADDR_ANY; server.sin_port=htons((unsigned short)51717); if (bind(sock,(struct sockaddr *)&server,length)<0) error("binding"); while (1) { n = recvfrom(sock,buf,BUFSIZE,0,(struct sockaddr *)&from,&fromlen); if (n < 0) error("recvfrom"); buf[n]='\0'; printf("The message from %s is %s\n", inet_ntoa((struct in_addr)from.sin_addr), buf); n = sendto(sock,"Got your message",16,0,(struct sockaddr *)&from,fromlen); if (n < 0) error("sendto"); } return 0; } void error(char *msg) { perror(msg); exit(0); }