//---------------------------------------------------------------- // tcpclient.cpp // // This program demonstrates the programming steps needed in // order that a TCP network-client application can establish // a connection with a server-program using a specific port. // This client sends one character to the server, then reads // back and displays a single-character response. (The user // supplies the server hostname as a command-line argument.) // // compile using: $ g++ tcpclient.cpp -o tcpclient // execute using: $ ./tcpclient // // programmer: ALLAN CRUSE // written on: 15 JAN 2002 // revised on: 13 APR 2008 //---------------------------------------------------------------- #include // for socket() #include // for PF_INET, SOCK_STREAM, IPPROTO_TCP #include // for gethostbyname() #include // for printf(), perror() #include // for bzero(), bcopy() #include // for read(), write(), close() #define DEMO_PORT 9734 int main( int argc, char *argv[] ) { //------------------------------------------------ // Get host information for the designated server //------------------------------------------------ if ( argc == 1 ) { fprintf( stderr, "must specify hostname\n" ); return -1; } struct hostent *hp = gethostbyname( argv[1] ); if ( !hp ) { fprintf( stderr, "%s: unknown host\n", argv[1] ); return -1; } //------------------------------------ // create the socket on which to send //------------------------------------ int sock = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP ); if ( sock < 0 ) { perror( "opening stream socket" ); return -1; } printf( "\nsock=%d \n", sock ); //------------------------- // construct a socket name //------------------------- struct sockaddr_in name; socklen_t nlen = sizeof name; bzero( &name, nlen ); bcopy( hp->h_addr, &name.sin_addr, hp->h_length ); name.sin_family = AF_INET; name.sin_port = htons( DEMO_PORT ); //---------------------------------------- // Establish a connection with the server //---------------------------------------- if ( connect( sock, (sockaddr *)&name, nlen ) < 0 ) { fprintf( stderr, "cannot connect\n" ); return -1; } printf( "connect succeeded\n" ); //-------------------------------------------------------- // write a character to the socket, then read a character //-------------------------------------------------------- char ch = 'A'; write( sock, &ch, 1 ); printf( "transmitted \'%c\' \n", ch ); read( sock, &ch, 1 ); printf( "received \'%c\' \n", ch ); //------------------------------------------------ // close the connection to the server-application //------------------------------------------------ close( sock ); printf( "\n" ); }