// File name : tcp.C // by Ee-Chien Chang //--------------------------------------------------------- // T C P routines //--------------------------------------------------------- // Open a socket for the client and // return a stream for the client //--------------------------------------------------------- // usage // FILE *fp; // int sd = establishconnection // ( "granny.cs.nyu.edu", 1222, // &(fp) ) // ..... // close (fp ); // close (sd ); //---------------------------------------------------------- // // //---------------------------------------------------------- #include #include #include #include #include #include #include #include #include #include /* read(), write(), close() */ #define SIZE 256 /* max length of a string */ #define MAXLINES 40 /* number of screen lines printed */ #define CR 13 #define LF 10 int open_socket(char *host, char *cmd, int port_number ); void out_usage(); int establish_connection ( char *host, int port_number , FILE **fp ) { int sd = -1; sd = open_socket ( host, host, port_number ); fp[0] = fdopen(sd,"r"); return (sd); } int open_socket(char *host, char *cmd, int port_number ) /* Create a socket. Assign host's details to name. Create a stream using name and connect the socket to it. */ { struct sockaddr_in name; struct hostent *hptr; int sd; int flag = -1; for (int i = 0 ; flag < 0 && i < 5 ; i ++ ) { // cout << "trying to establish connection " << endl; sd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sd < 0) { perror( "Open Socket failed:"); out_usage(); exit(1); } name.sin_family = AF_INET; name.sin_port = htons(port_number); /* 80 for HTTP server */ if ((hptr = gethostbyname(host)) == NULL) { perror("gethostbyname"); out_usage(); exit(1); } /* copy the IP address of host into name */ // printf ( " name of host %s lenght %d\n",hptr->h_name, hptr->h_length); bcopy(hptr->h_addr, &name.sin_addr.s_addr, hptr->h_length); printf("Trying to contact %s...\n", host); flag = connect(sd, (sockaddr *)&name, sizeof(name)) ; if (flag<0) { sleep(1); // cout << "try again" << endl; } } // cout << "here...." << flag << endl; if (flag < 0 ) { perror ("no connection:"); close(sd); out_usage(); exit(1); } return sd; } void out_usage() { cerr << "Usage:" << endl << "\tclient [-p port_number] [server_name]" << endl << endl << "\tserver_name :\t the name of the server" << endl << "\t\t\t(default server: brutus.ams.sunysb.edu" << endl << "\t\t\t defualt port number: 1222)" << endl; }