|  | 
 
| [code:1] /* Whoisserver.c */
 
 #include <stdio.h>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <netdb.h>
 #include <pwd.h>
 
 #define BACKLOG                5
 #define MAXHOSTNAME        32
 
 main(argc, argv)
 int argc;
 char *argv[];
 {
 
 int s, t;
 int i;
 struct sockaddr_in sa, isa;
 struct hostent *hp;
 char *myname;
 struct servent *sp;
 char localhost[MAXHOSTNAME + 1];
 
 myname = argv[0];
 
 if ((sp = getservbyname("whois", "tcp")) == NULL) {
 fprintf(stderr, "%s: NO whois service on this host\n", myname);
 exit(1);
 }
 
 gethostname(localhost, MAXHOSTNAME);
 if ((hp = gethostbyname(localhost)) == NULL) {
 fprintf(stderr, "%s: cannot get local host info?\n", myname);
 exit(1);
 }
 
 sa.sin_port = sp->s_port;
 bcopy((char *)hp->h_addr, (char *)&sa.sin_addr, hp->h_length);
 sa.sin_family = hp->h_addrtype;
 
 if ((s = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0) {
 perror("socket");
 exit(1);
 }
 
 if (bind(s, (struct sockaddr * ) &sa, sizeof(sa)) < 0) {
 perror("bind");
 exit(1);
 }
 
 listen(s, BACKLOG);
 
 while(1) {
 i = sizeof(isa);
 if ((t = accept(s, (struct sockaddr *) &isa, &i)) < 0) {
 perror("accept");
 exit(1);
 }
 
 whois(t);
 close(t);
 }
 }
 
 whois(sock)
 int sock;
 {
 struct passwd *p;
 char buf[BUFSIZ];
 int i;
 
 if ((i = read(sock, buf, BUFSIZ)) <= 0) return;
 
 buf[i] = ' ';
 
 if ((p = getpwnam(buf)) == NULL)
 strcpy(buf, "Hi,User not found\n");
 else
 sprintf(buf, "%s: %s\n", p->pw_name, p->pw_gecos);
 
 write(sock, buf, strlen(buf));
 return;
 }
 
 /* End of whoisserver */
 
 /* Whoisclient.c */
 
 #include <stdio.h>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <netdb.h>
 
 main(argc, argv)
 int argc;
 char *argv[];
 {
 int s;
 int len;
 struct sockaddr_in sa;
 struct hostent *hp;
 struct servent *sp;
 char buf[BUFSIZ];
 char *myname;
 char *host;
 char *user;
 
 myname = argv[0];
 
 if (argc != 3) {
 fprintf(stderr, "Usage: %s host uname\n", myname);
 exit(1);
 }
 
 host = argv[1];
 user = argv[2];
 
 if ((hp = gethostbyname(host)) == NULL) {
 fprintf(stderr, "%s: %s: no such host?", myname, host);
 exit(1);
 }
 
 bcopy((char *)hp->h_addr, (char *) &sa.sin_addr, hp->h_length);
 sa.sin_family = hp->h_addrtype;
 
 
 if ((sp = getservbyname("whois", "tcp")) == NULL) {
 fprintf(stderr, "%s: No whois service on this host\n", myname);
 exit(1);
 }
 sa.sin_port = sp->s_port;
 
 if ((s = socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0) {
 perror("socket");
 exit(1);
 }
 
 if (connect(s, (struct sockaddr * ) &sa, sizeof(sa)) < 0) {
 perror("connect");
 exit(1);
 }
 
 if (write(s, user, strlen(user)) != strlen(user)) {
 fprintf(stderr, "%s: write error\n", myname);
 exit(1);
 }
 
 while((len = read(s, buf, BUFSIZ)) > 0) write(0, buf, len);
 
 close(s);
 exit(0);
 }
 /*end of who is client*/
 [/code:1]
 | 
 |