dgrecv.c
1 /**************************************************************** 2 * dgrecv.c - datagram receiver 3 * usage: dgrecv portnum 4 * action: listens at the specfied port and reports messages 5 */ 6 #include <stdio.h> 7 #include <stdlib.h> 8 #include <sys/types.h> 9 #include <sys/socket.h> 10 #include <netinet/in.h> 11 #include <netdb.h> 12 #include <string.h> 13 #include <arpa/inet.h> 14 #include <unistd.h> 15 16 #define oops(m,x) {perror(m); exit(x);} 17 18 int make_dgram_server_socket(int); 19 int get_internet_address(char* , int , int *, struct sockaddr_in *); 20 void say_who_called(struct sockaddr_in* ); 21 22 int main(int argc, char* argv[]) { 23 int port; 24 int sock; 25 char buf[BUFSIZ]; 26 size_t msglen; 27 struct sockaddr_in saddr; 28 socklen_t saddrlen; 29 30 if(argc==1 || (port=atoi(argv[1]))<=0){ 31 fprintf(stderr, "usage :dgrecv portnumber "); 32 exit(1); 33 } 34 35 /*get a socket and assign it a port number*/ 36 if((sock=make_dgram_server_socket(port))==-1) 37 oops("cannot make server", 2); 38 39 /*receive messages on that socket*/ 40 saddrlen=sizeof(saddr); 41 while((msglen=recvfrom(sock ,buf, BUFSIZ, 0, &saddr, &saddrlen))>0) { 42 buf[msglen]='