//--------------------------------------------------------- // 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 #ifdef SUN #include #endif #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 ); 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; while (flag < 0 ) { cout << "trying to establish connection " << endl; sd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if (sd < 0) { perror( "Open Socket failed:"); exit(1); } name.sin_family = PF_INET; name.sin_port = htons(port_number); /* 80 for HTTP server */ if ((hptr = gethostbyname(host)) == NULL) { perror("gethostbyname"); 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; } } char alive = 1; setsockopt(sd, IPPROTO_TCP, SO_KEEPALIVE, &alive, (int) sizeof(alive)); cout << "here...." << flag << endl; if (flag >= 0 ) { cout << "success" << endl; } else { perror ("no connection:"); close(sd); perror("connection failed:"); exit(1); } return sd; }