













Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!














#include "TCPEchoServer.h" /* TCP echo server includes / #include <sys/time.h> / for struct timeval {} / #include <fcntl.h> / for fcntl() */
int main(int argc, char *argv[]) { int servSock; / Socket descriptors for server / int maxDescriptor; / Maximum socket descriptor value / fd_set sockSet; / Set of socket descriptors for select() / long timeout; / Timeout value given on command-line / struct timeval selTimeout; / Timeout for select() / int running = 1; / 1 if server should be running; 0 otherwise / int noPorts; / Number of port specified on command-line / int port; / Looping variable for ports / unsigned short portNo; / Actual port number */
if (argc < 3) /* Test for correct number of arguments */ { fprintf(stderr, "Usage: %s <Timeout (secs.)> <Port 1> ...\n", argv[0]); exit(1); }
timeout = atol(argv[1]); /* First arg: Timeout / noPorts = argc - 2; / Number of ports is argument count minus 2 */
/* Allocate list of sockets for incoming connections */ servSock = (int ) malloc(noPorts * sizeof(int)); / Initialize maxDescriptor for use by select() */ maxDescriptor = -1;
/* Create list of ports and sockets to handle ports / for (port = 0; port < noPorts; port++) { / Add port to port list / portNo = atoi(argv[port + 2]); / Skip first two arguments */
/* Create port socket */ servSock[port] = CreateTCPServerSocket(portNo);
/* Determine if new descriptor is the largest */ if (servSock[port] > maxDescriptor) maxDescriptor = servSock[port]; }
printf("Starting server: Hit return to shutdown\n"); while (running) { /* Zero socket descriptor vector and set for server sockets / / This must be reset every time select() is called / FD_ZERO(&sockSet); / Add keyboard to descriptor vector */ FD_SET(STDIN_FILENO, &sockSet); for (port = 0; port < noPorts; port++)
FD_SET(servSock[port], &sockSet);
/* Timeout specification / / This must be reset every time select() is called / selTimeout.tv_sec = timeout; / timeout (secs.) / selTimeout.tv_usec = 0; / 0 microseconds */
/* Suspend program until descriptor is ready or timeout / if (select(maxDescriptor + 1, &sockSet, NULL, NULL, &selTimeout) == 0) printf("No echo requests for %ld secs...Server still alive \n", timeout); else { if (FD_ISSET(0, &sockSet)) / Check keyboard */ { printf("Shutting down server\n"); getchar(); running = 0; }
for (port = 0; port < noPorts; port++) if (FD_ISSET(servSock[port], &sockSet)) { printf("Request on port %d: ", port); HandleTCPClient(AcceptTCPConnection(servSock [port])); } } }
/* Close sockets */ for (port = 0; port < noPorts; port++) close(servSock[port]);
/* Free list of sockets */ free(servSock);
exit(0); }
/* connected-peer.c
int SetAddress(char* Composite, struct sockaddr_in *Addr) { int i; char IPAddress[MAXIP];
bzero(Addr, sizeof(*Addr)); Addr->sin_family = AF_INET; for ( i = 0; Composite[i] != ':' && Composite[i] != 0 && i < MAXIP; i++ ) IPAddress[i] = Composite[i]; IPAddress[i] = 0; if ( Composite[i] == ':' ) Addr->sin_port = htons(atoi(Composite+i+1)); else Addr->sin_port = 0; if ( *IPAddress == 0 ) { Addr->sin_addr.s_addr = INADDR_ANY; return 0; } else return ( inet_aton(IPAddress, &Addr->sin_addr) == 0 ); }
/* main / / / / Open socket, connect and receive messages / /-------------------------------------------------------------------- */ int main(int Count, char *Strings[]) { int sd; struct sockaddr_in addr;
if ( Count < 3 || Count > 4 ) { printf("usage: coupled-peer
perror(Strings[2]); exit(errno); } if ( connect(sd, (struct sockaddr *)&addr, sizeof(addr)) != 0 ) { perror("Connect"); exit(errno); } if ( Count == 4 ) send(sd, Strings[3], strlen(Strings[3]), 0); while (1) { int bytes_read;
bzero(buffer, sizeof(buffer)); bytes_read = recv(sd, buffer, sizeof(buffer), 0); if ( bytes_read > 0 ) { printf("Msg: %s\n", buffer); sleep(1); send(sd, buffer, bytes_read, 0); } } close(sd); return 0; }
connectionless-receiver.c
/*** connectionless-receiver.c ***/
while ( bytes_read > 0 ); close(sd); return 0; }
/* ttcp-client.c
/*** ttcp-client.c / / / / Test transaction-TCP (T/TCP) support. ***/ /
*******/
#include <stdio.h> #include <errno.h> #include <sys/socket.h> #include <resolv.h>
#define DEFAULT_PORT 9999
#ifndef TCP_NOPUSH #error TCP_NOPUSH not defined #endif #ifndef MSG_FIN #error MSG_FIN or MSG_EOF not defined #endif
void PANIC(char *msg); #define PANIC(msg) {perror(msg);abort();}
/ --------------------------------------------------------------------- / /--- main - try to connect to a t/tcp server. ---/ / *--------------------------------------------------------------------- */ int main(int count, char *strings[]) { int sd; int port=DEFAULT_PORT; char *host="127.0.0.1"; struct sockaddr_in addr; int addr_len = sizeof(addr); char buffer[1024];
if ( count == 3 ) { port = atoi(strings[2]); host = strings[1]; } else printf("usage: %s <server's address> <server's port> \n...using default port (%d)\n", strings[0], port); sd = socket(PF_INET, SOCK_STREAM, 0);
/---Set destination address---/ bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); inet_aton(host, &addr.sin_addr);
/---Send message using directed protocol---/ if ( sendto(sd, "sean\n", 5, 0, (struct sockaddr*)&addr, sizeof (addr)) < 0 ) PANIC("sendto"); bzero(buffer, sizeof(buffer));
/---Get message using directed protocol---/ recvfrom(sd, buffer, sizeof(buffer), 0, (struct sockaddr*)&addr, &addr_len); printf("%s\n", buffer); close(sd); }
/* ttcp-server.c
int client = accept(sd, 0, 0); printf("connected\n"); send(client, buffer, recv(client, buffer, sizeof (buffer), 0), 0); close(client); } return 0; } /* echo-thread.c
/*** echo-thread.c / / / / An echo server using threads. ***/ /
*******/ #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/socket.h> #include <resolv.h> #include <arpa/inet.h> #include <pthread.h>
void PANIC(char* msg);
#define PANIC(msg) { perror(msg); exit(-1); }
/--- Child - echo servlet --- / /-------------------------------------------------------------------- / void Child(void arg) { char line[100]; int bytes_read; int client = *(int *)arg;
do { bytes_read = recv(client, line, sizeof(line), 0); send(client, line, bytes_read, 0); } while (strncmp(line, "bye\r", 4) != 0); close(client); return arg; }
/*--- main - setup server and await connections (no need to clean --- / /--- up after terminated children. --- / /-------------------------------------------------------------------- */ int main(void) { int sd; struct sockaddr_in addr;
if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0 ) PANIC("Socket"); addr.sin_family = AF_INET; addr.sin_port = htons(9999); addr.sin_addr.s_addr = INADDR_ANY; if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 ) PANIC("Bind"); if ( listen(sd, 20) != 0 ) PANIC("Listen"); while (1) { int client, addr_size = sizeof(addr); pthread_t child;
client = accept(sd, (struct sockaddr)&addr, &addr_size); printf("Connected: %s:%d\n", inet_ntoa(addr.sin_addr), ntohs (addr.sin_port)); if ( pthread_create(&child, NULL, Child, &client) != 0 ) perror("Thread creation"); else pthread_detach(child); / disassociate from parent */ } return 0; }
/* smart-select.c
void sig_child(int signum) { wait(0); NumChildren--; }
/ --------------------------------------------------------------------- / /--- servlet - each servlet accepts a connection and keeps track ---/ /--- of it using a select() statement. ---/ / *--------------------------------------------------------------------- */ void servlet(int server) { fd_set set; int maxfd = server; int ceiling=0;
FD_ZERO(&set); FD_SET(server, &set); for (;;) { struct timeval timeout={2,0}; /* 2 seconds */
/---Wait for some action---/ if ( select(maxfd+1, &set, 0, 0, &timeout) > 0 ) { /---If new connection, connect and add to list---/ if ( FD_ISSET(server, &set) ) { if ( ceiling < MAXCONNECTIONS ) { int client = accept(server, 0, 0); if ( maxfd < client ) maxfd = client; FD_SET(client, &set); ceiling++; printf("select process #%d: %d connected\n", getpid(), ceiling); } }
/---If command/request from client, process---/ else { int i;
for ( i = 0; i < maxfd+1; i++ ) { if ( FD_ISSET(i, &set) ) { char buffer[1024]; int bytes;
bytes = recv(i, buffer, sizeof(buffer), 0);
if ( bytes < 0 ) /* check if channel closed / { close(i); FD_CLR(i, &set); ceiling--; printf("select process #%d: %d connected\n", ge tpid(), ceiling); } else / process the request */ send(i, buffer, bytes, 0); } } } } } exit(0); }
/--- main - set up server and maintain the number of living servlets--/ / *--------------------------------------------------------------------- */ int main(int count, char *strings[]) { int sd; struct sockaddr_in addr; struct sigaction act;
if ( count != 2 ) { printf("usage: %s
sd = socket(PF_INET, SOCK_STREAM, 0); bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(atoi(strings[1])); addr.sin_addr.s_addr = INADDR_ANY; if ( bind(sd, (struct sockaddr*)&addr, sizeof(addr)) == 0 ) { listen(sd, 15); for (;;) { if ( NumChildren < MAXPROCESSES ) { int pid;
if ( (pid = fork()) == 0 )
#include <resolv.h> #include <unistd.h> #include <signal.h> #include <sys/time.h>
#define MAXPROCESSES 5 #define MAXCONNECTIONS 5
int NumChildren=0;
/--- sig_child - SIGCHLD ---/ / *--------------------------------------------------------------------- */ void sig_child(int signum) { wait(0); NumChildren--; }
/ --------------------------------------------------------------------- / /--- servlet - each servlet accepts a connection and keeps track ---/ /--- of it using a select() statement. ---/ / *--------------------------------------------------------------------- */ void servlet(int server) { fd_set set; int maxfd = server; int ceiling=0;
FD_ZERO(&set); FD_SET(server, &set); for (;;) { struct timeval timeout={2,0}; /* 2 seconds */
/---Wait for some action---/ if ( select(maxfd+1, &set, 0, 0, &timeout) > 0 ) { /---If new connection, connect and add to list---/ if ( FD_ISSET(server, &set) ) { if ( ceiling < MAXCONNECTIONS ) { int client = accept(server, 0, 0); if ( maxfd < client ) maxfd = client; FD_SET(client, &set); ceiling++; printf("select process #%d: %d connected\n", getpid(), ceiling); }
/---If command/request from client, process---/ else { int i;
for ( i = 0; i < maxfd+1; i++ ) { if ( FD_ISSET(i, &set) ) { char buffer[1024]; int bytes;
bytes = recv(i, buffer, sizeof(buffer), 0); if ( bytes < 0 ) /* check if channel closed / { close(i); FD_CLR(i, &set); ceiling--; printf("select process #%d: %d connected\n", ge tpid(), ceiling); } else / process the request */ send(i, buffer, bytes, 0); } } } } } exit(0); }
/--- main - set up server and maintain the number of living servlets--/ / *--------------------------------------------------------------------- */ int main(int count, char *strings[]) { int sd; struct sockaddr_in addr; struct sigaction act;
if ( count != 2 ) { printf("usage: %s
printf("Usage: server MYIP PORT\n"); exit (1); }
/********get server host name, and port number */ port = atoi(argv[2]); //PORT from command line if(port<=1023){ printf("Port %d is reserved, select # >1023\n",port); exit (1); } printf("PORT NUMBER: %d\n", port);
/*********set protocol to TCP*/ protocol = getprotobyname("tcp"); if(protocol==NULL){ printf("protocol error\n"); }
/*********get host from command line--IP number*/ if((host = gethostbyname(argv[1]))==NULL){ printf("host error: %d\n",h_errno); exit (1); }
bzero(&passive, sizeof(passive)); passive.sin_family = host->h_addrtype; passive.sin_port = htons(port); bcopy(host->h_addr, &passive.sin_addr, host->h_length);
/*********set up socket for listening*/ if((skt=socket(AF_INET, SOCK_STREAM, protocol->p_proto))==-1){ printf("socket error\n"); exit (1); }
/* fcntl(skt,F_SETFL,O_NONBLOCK); set socket to nonblock read*/
/********Bind the listener to socket / if(bind(skt,(struct sockaddr) &passive, sizeof(passive))==-1) { printf("Bind error: %d... restart\n",errno); exit(1); }
if(listen(skt, MAXCLIENTS)){ printf("Listen failed\n"); exit(1); } printf("Server is now listening\n"); printf(">"); fflush(NULL);
while(1){ int i; int j; int n; /********RECREATE FD_SET...select value-result parameter rfds/ FD_ZERO(&rfds); FD_SET(0,&rfds); /mark stdin (0=stdin,1=stdout,2=stderr/ FD_SET(skt, &rfds); /mark the bound socket=3/ for(i=0; i<=num_clients; i++) /mark all client sockets*/ FD_SET(sockets[i],&rfds);
/"select"- monitors all communication sockets, listening skt, and stdin/ if( (retval=select(FD_SETSIZE, &rfds, NULL,NULL,NULL)) == -1) { perror("select error"); }
/*******find out what is ready************/ if(FD_ISSET(0,&rfds)){ /(0=stdin,1=stdout,2=stderr)/ fgets(outbuf,BUFLEN,stdin); if(strcmp(outbuf,"quit\n")==0){ sprintf(outbuf, "\nSESSION TERMINATED BY SERVER \n"); for(j=0; j<=num_clients;j++){ send(sockets[j], outbuf, strlen(&outbuf[0]) +1,0); } goto closing; } printf(">"); fflush(NULL); } else if(FD_ISSET(skt, &rfds)){ /client requests/ printf("\nADDING CLIENT %d\n",num_clients); activeLen=sizeof(active); if((newSkt=accept(skt,(struct sockaddr)&active, &activeLen))==-1){ printf("\nClient %d Accept error\n>",num_clients); } else { sockets[num_clients]=newSkt; } sprintf(outbuf, "CLIENT %d IS OPEN FOR COMMUNICATION \n",num_clients); for(j=0; j<num_clients;j++){ send(sockets[j], outbuf, strlen(&outbuf[0])+1,0); } printf(">"); fflush(NULL); FD_SET(sockets[num_clients], &rfds); num_clients++; } else{ for(n=0; n<=num_clients; n++){ /check all bits/ if(FD_ISSET(sockets[n],&rfds)){ /to see if changed/ inbuf[recv(sockets[n], inbuf, BUFSIZ, 0)]='\0'; if(strcmp(inbuf, "\nSESSION TERMINATED BY CLIENT* \n")==0){ printf("Client %d's session has terminated\n",n); sprintf(outbuf,"SESSION TERMED BY CLIENT %d\n",n); for(j=0; j<=num_clients;j++){ if(j!=n) send(sockets[j], outbuf, strlen(&outbuf[0]) +1,0); } printf(">"); fflush(NULL); goto closesocket; } printf("RECEIVING FROM CLIENT %d\n",n); printf("\t%s\n",inbuf); sprintf(outbuf,"%d<%s",n,inbuf); /printf("send to clients: %s\n",inbuf);/ for(j=0; j<num_clients;j++){