1 /***********************************************************
2 * Capitalization server.
3 * This server just changes lower case letters to capitals.
4 * It always listens on port 10000.
5 ***********************************************************/
6 #include <sys/types.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <sys/socket.h>
10 #include <netinet/in.h>
11 #include <arpa/inet.h>
12 #include <netdb.h>
13
14 int main(int argc, char **argv)
15 {
16 /* Get IP address of current host. */
17 struct hostent *p;
18 p = gethostbyname(getenv("HOST"));
19 if (p == NULL) { fprintf(stderr,"Name not found!\n"); exit(1); }
20 unsigned int *ip = (unsigned int*)(p->h_addr_list[0]);
21
22 /* Set up socket */
23 int sfd = socket(AF_INET,SOCK_STREAM,0);
24 if (sfd == -1) { fprintf(stderr,"Socket not created!\n"); exit(2); }
25
26 /* Set up address structure */
27 struct sockaddr_in mysa;
28 mysa.sin_family = AF_INET;
29 mysa.sin_addr.s_addr = *ip;
30 mysa.sin_port = htons(10000);
31
32 /* Bind socket to address */
33 if (bind(sfd,(struct sockaddr*)&mysa,sizeof(mysa)) < 0)
34 {
35 close(sfd);
36 fprintf(stderr,"bind failed!\n");
37 exit(3);
38 }
39
40 /* Listen for connection request */
41 if (listen(sfd,20) < 0)
42 {
43 close(sfd);
44 fprintf(stderr,"listen failed!\n");
45 exit(4);
46 }
47
48 /* Accept the connection request */
49 while(1)
50 {
51 int sessionfd = accept(sfd,NULL,NULL);
52 if (sessionfd == -1)
53 {
54 close(sfd);
55 fprintf(stderr,"accept failed!\n");
56 exit(5);
57 }
58
59 /* fork a child to serve this connection. */
60 if (fork() == 0)
61 {
62 char inc, outc;
63 while(read(sessionfd,&inc,1) == 1)
64 {
65 if ('a' <= inc && inc <= 'z')
66 outc = inc - 'a' + 'A';
67 else
68 outc = inc;
69 write(sessionfd,&outc,1);
70 }
71 close(sessionfd);
72 exit(1);
73 }
74 else
75 {
76 close(sessionfd);
77 }
78 }
79 fprintf(stderr,"Server shutting down!\n");
80 close(sfd);
81 return 0;
82 }