//------------------------------------------------------------------- // getquote.cpp // // This program reimplements using C++ the functionality of our // earlier Python demo-program named 'getquote.py', affording a // better view of the underlying 'sockets' programing interface // which the Python language intentionally 'hides' from a user. // // compile using: $ g++ getquote.cpp -o getquote // execute using: $ ./getquote // // programmer: ALLAN CRUSE // date begun: 27 JAN 2009 // completion: 28 JAN 2009 // revised on: 03 FEB 2009 //------------------------------------------------------------------- #include // for gethostbyname() #include // for printf(), perror() #include // for bzero(), bcopy(), strtok() #include // for exit() int main( int argc, char **argv ) { char host[] = "download.finance.yahoo.com"; int port = 80; int sock = socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); if ( sock < 0) { perror( "socket" ); exit(1); } struct timeval tval = { 1, 0 } ; socklen_t tlen = sizeof( tval ); if ( setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO, &tval, tlen ) < 0 ) { perror( "setsockopt" ); exit(1); } struct hostent *hp = gethostbyname( host ); if ( !hp ) { herror( "gethostbyname" ); exit(1); } struct sockaddr_in saddr; socklen_t salen = sizeof( saddr ); bzero( &saddr, salen ); saddr.sin_family = AF_INET; saddr.sin_port = htons( port ); bcopy( hp->h_addr, &saddr.sin_addr, hp->h_length ); if ( connect( sock, (sockaddr*)&saddr, salen ) < 0 ) { perror( "connect" ); exit(1); } char msg[] = "GET /d/quotes.cvs?s=INTC&f=sl1d1t1c1ohgv&e=.csv \r\n"; int mlen = strlen( msg ); if ( send( sock, msg, mlen, 0 ) < 0 ) { perror( "send" ); exit(1); } if ( send( sock, "\r\n", 2, 0 ) < 0 ) { perror( "send" ); exit(1); } char buf[ 4096 ] = {0}; if ( recv( sock, buf, 4096, 0 ) < 0 ) { perror( "recv" ); exit(1); } char *quote[ 9 ]; quote[ 0 ] = strtok( buf, ",\n" ); for (int i = 1; i < 9; i++) quote[ i ] = strtok( NULL, ",\n" ); printf( "\n" ); printf( "Intel Stock: $%s at %s on %s\n", quote[1],quote[3],quote[2] ); printf( "\n" ); }