//---------------------------------------------------------------- // txalpha.cpp // // // compile using: $ g++ txalpha.cpp -o txalpha // execute using: $ ./txalpha // // programmer: ALLAN CRUSE // written 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() #include // for open() #include // for mmap() #define DEMO_PORT 9734 char filename[] = "alphabet.dat"; 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" ); //--------------------- // open the image-file //--------------------- int fd = open( filename, O_RDONLY ); if ( fd < 0 ) { perror( filename ); return -1; } int size = lseek( fd, 0, SEEK_END ); int prot = PROT_READ; int flag = MAP_PRIVATE; void *img = mmap( NULL, size, prot, flag, fd, 0 ); if ( img == MAP_FAILED ) { perror( "mmap" ); return -1; } //------------------------------- // write the image to the socket //------------------------------- int nbytes = write( sock, img, size ); printf( "transmitted %d bytes \n", nbytes ); //------------------------------------------------ // close the connection to the server-application //------------------------------------------------ close( sock ); printf( "\n" ); }