/***********************************************************
* Capitalization server.
* This server just changes lower case letters to capitals.
* It always listens on port 10000.
***********************************************************/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
int main(int argc, char **argv)
{
/* Get IP address of current host. */
struct hostent *p;
p = gethostbyname(getenv("HOST"));
if (p == NULL) { fprintf(stderr,"Name not found!\n"); exit(1); }
unsigned int *ip = (unsigned int*)(p->h_addr_list[0]);
/* Set up socket */
int sfd = socket(AF_INET,SOCK_STREAM,0);
if (sfd == -1) { fprintf(stderr,"Socket not created!\n"); exit(2); }
/* Set up address structure */
struct sockaddr_in mysa;
mysa.sin_family = AF_INET;
mysa.sin_addr.s_addr = *ip;
mysa.sin_port = htons(10000);
/* Bind socket to address */
if (bind(sfd,(struct sockaddr*)&mysa,sizeof(mysa)) < 0)
{
close(sfd);
fprintf(stderr,"bind failed!\n");
exit(3);
}
/* Listen for connection request */
if (listen(sfd,20) < 0)
{
close(sfd);
fprintf(stderr,"listen failed!\n");
exit(4);
}
/* Accept the connection request */
while(1)
{
int sessionfd = accept(sfd,NULL,NULL);
if (sessionfd == -1)
{
close(sfd);
fprintf(stderr,"accept failed!\n");
exit(5);
}
/* fork a child to serve this connection. */
if (fork() == 0)
{
char inc, outc;
while(read(sessionfd,&inc,1) == 1)
{
if ('a' <= inc && inc <= 'z')
outc = inc - 'a' + 'A';
else
outc = inc;
write(sessionfd,&outc,1);
}
close(sessionfd);
exit(1);
}
else
{
close(sessionfd);
}
}
fprintf(stderr,"Server shutting down!\n");
close(sfd);
return 0;
}