#include #include #include #include #include #include #include #include "common.h" #include "procs.h" int main(int argc, char *argv[]) { int ssocket; /* server socket */ struct sockaddr_in server; /* server address */ struct procreg pr; /* procedure registry */ int running = 1; /* whether or not we continue looping (boolean) */ initprocreg(&pr); /* initialize the procedure registry */ /* get the server socket, check for error */ if((ssocket = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("couldn't create server socket"); exit(1); } bzero(&server, sizeof(server)); /* zero the address */ /* listen on any INET address at port PORT */ server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(PORT); /* bind the socket, check for error */ if(bind(ssocket, (struct sockaddr *)&server, sizeof(server)) == -1) { perror("couldn't bind socket"); close(ssocket); exit(1); } /* listen on the socket, check for error */ if(listen(ssocket, 1) == -1) { perror("couldn't listen on socket"); close(ssocket); exit(1); } while(running) { /* loop forever */ int csocket, addrlen; /* client socket and length of address */ struct sockaddr_in client; /* client address */ char buffer[BLEN]; /* socket buffer */ fprintf(stderr, "waiting for connection\n"); /* accept an incoming connection, check for error */ addrlen = sizeof(client); if((csocket = accept(ssocket, (struct sockaddr *)&client, &addrlen)) == -1) { perror("couldn't accept connection"); close(ssocket); exit(1); } printf("connected!\n"); /* receive data into the buffer, check for error */ if(read(csocket, buffer, BLEN) == -1) { perror("couldn't read from socket"); close(ssocket); exit(1); } /* see what the client wants */ if(strncasecmp(buffer, "Q\n", 2) == 0) { /* got a 'quit' */ printf("received a quit, exiting\n"); write(csocket, "OK\n", 4); /* acknowledge client */ running = 0; /* don't loop next time */ } else if(strncasecmp(buffer, "L\n", 2) == 0) { /* got a 'listregistry' */ /* list the proc registry to the client */ listregistry(pr, csocket); } else if(strncasecmp(buffer, "E", 1) == 0) { /* got an 'execute' */ /* attempt to call the desired procedure, check for error */ if(!prcall(pr, buffer, csocket)) { write(csocket, "bad procedure call\n", 34); } } else { printf("received unknown command\n"); /* tell the client we don't know what it means */ write(csocket, "unknown command\n", 17); } close(csocket); /* close the client socket */ } return 0; }