/* svudp.c Server code, UDP, from Padovano, "Networking Applications on Unix System V Release 4", Prentice-Hall, page 514 .. (with minor modification to allow system selected port) This program is called as follows svudp & and it will print out a port number. svudp when queried by a client with a user name, say fowler, reports to the client if fowler is or not logged on this machine. */ #include #include #include #include /* #define SERV_PORT 2345 */ #define MAXNAME 1024 main() { int dg_fd; /* file descriptor into UDP */ struct sockaddr_in myaddr; /* the addr of this service */ int len; /* length of address */ char buff[MAXNAME]; /* buffer to hold datagram */ char reply; /* response to the client */ struct sockaddr_in client_addr; /* the addr of client */ char cmd[BUFSIZ]; /* Variables used to figure */ char junkbuf[BUFSIZ]; /* if user is logged onto */ FILE *fp; /* the system */ /* Open a socket into UDP/IP */ if ((dg_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket failed"); exit(1); } /* Set up our address */ bzero((char *)&myaddr, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = 0; /*htons(SERV_PORT);*/ /* Bind to the address of this service */ if (bind(dg_fd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0) { perror("bind failed"); exit(1); } /* Print port number */ len = sizeof(myaddr); if (getsockname(dg_fd, (struct sockaddr *)&myaddr, &len) < 0) { perror("Error getting socketname \n"); exit(1); } printf("Socket port #%d\n", ntohs(myaddr.sin_port)); /* Loop continuously, processing datagrams. */ len = sizeof(struct sockaddr); while (1) { if(recvfrom(dg_fd, buff, MAXNAME, 0, &client_addr, &len) < 0) { perror("could not read datagram"); continue; } sprintf(cmd, "who | grep '^%s '", buff); if ((fp = popen(cmd, "r")) == NULL || fgets(junkbuf, BUFSIZ, fp) == NULL) { reply = 'n'; } else { reply = 'y'; } if (sendto(dg_fd, &reply, 1, 0, &client_addr, len) < 0) { perror("continue not send datagram!"); continue; } } }