// internet_server.cpp #include "includes.h" #include "internet_server.h" int internet_server::session_count=0; extern int errno; internet_server::internet_server(void) { session_count+=1; session_number=session_count; allOK=false; make_socket_connected_to_random_port(); printf("[server established on port %d]\n",port_number); signal(SIGCHLD,(sig_t)internet_server::server_subprocess_reaper); signal(SIGINT,(sig_t)internet_server::received_halt_signal); allOK=true; } void internet_server::server_subprocess_reaper(void) { int process_id,exit_status; process_id=wait(&exit_status); } void internet_server::received_halt_signal(void) { int r; signal(SIGINT,SIG_DFL); printf("[Received halt signal, waiting for subprocesses]\n"); do r=wait(NULL); while (r!=-1); printf("[Server terminated]\n"); exit(2); } int internet_server::getSessionNumber(void) { return session_number; } char *internet_server::getClientName(void) { strcpy(templine,client_name); return templine; } void internet_server::make_socket_connected_to_random_port(void) { int r; struct sockaddr_in my_connection_info; struct sockaddr *mci_ptr=(struct sockaddr *)&my_connection_info; const int mci_size=sizeof(my_connection_info); time_t now=time(NULL); srand(now^getpid()); server_socket=socket(AF_INET,SOCK_STREAM,0); if (server_socket<0) { fprintf(stderr,"Can't create socket\n"); perror(""); exit(1); } do { port_number=1024+(rand() & 0x1FFF); bzero(mci_ptr,mci_size); my_connection_info.sin_family=AF_INET; my_connection_info.sin_addr.s_addr=htonl(INADDR_ANY); my_connection_info.sin_port=htons(port_number); r=bind(server_socket,mci_ptr,mci_size); } while (r<0); r=listen(server_socket,3); if (r<0) { fprintf(stderr,"Failure while listening"); perror(""); exit(1); } } void internet_server::waitforuser(void) { while (1) { long int client_ip_addr; struct sockaddr_in client_info; struct sockaddr *ci_ptr=(struct sockaddr *)&client_info; int ci_size=sizeof(client_info); session_socket=accept(server_socket,ci_ptr,&ci_size); if (session_socket<0) { if (errno==EINTR) continue; perror("accept"); sleep(1); continue; } session_number+=1; if (fork()==0) { struct in_addr client_addr; client_addr.s_addr=client_info.sin_addr.s_addr; strcpy(client_name,inet_ntoa(client_addr)); printf("[connection accepted from %s: session %d]\n", client_name, session_number); read_file=fdopen(session_socket,"r"); write_file=fdopen(session_socket,"w"); if (read_file==NULL || write_file==NULL) { printf("[bad connection, session %d terminated]\n", session_number); exit(1); } return; } close(session_socket); } } void internet_server::disconnect(void) { exit(0); }