#include #include #include #include #include #include int construct_socket(); char *get_query(char *host, char *page); #define HOST "divine.fi.muni.cz" #define PAGE "/" #define PORT 0x5000u #define USERAGENT "HTMLGET 1.0" // the address of divine.fi.muni.cz #define ADDR 0xa133fb93 /* declare a few things currently missing from DIVINE's libc */ struct in_addr { uint32_t s_addr; }; struct sockaddr_in { short sin_family; // e.g. AF_INET unsigned short sin_port; // e.g. htons(3490) struct in_addr sin_addr; // see struct in_addr, below char sin_zero[8]; // zero this if you want to }; int main(int argc, char **argv) { struct sockaddr_in *remote; int socket; int actionResult; char *query; char buffer[ BUFSIZ + 1 ]; socket = construct_socket(); remote = (struct sockaddr_in *)malloc( sizeof( struct sockaddr_in ) ); if ( !remote ) return 1; remote->sin_family = AF_INET; remote->sin_addr.s_addr = ADDR; memset( remote->sin_zero, 0, 8 ); remote->sin_port = PORT; if ( connect( socket, ( struct sockaddr * )remote, sizeof( struct sockaddr ) ) < 0 ) { perror( "Error: Could not connect" ); exit( 1 ); } query = get_query( HOST, PAGE ); fprintf( stderr, "Query is:\n<>\n%s<>\n", query ); int sent = 0; while ( sent < strlen( query ) ) { actionResult = send( socket, query+sent, strlen( query ) - sent, 0 ); if ( actionResult == -1 ) { perror( "Error: Can't send query" ); exit( 1 ); } sent += actionResult; } memset( buffer, 0, sizeof( buffer ) ); int htmlStart = 0; char *htmlContent = NULL; while( ( actionResult = recv( socket, buffer, BUFSIZ, 0 ) ) > 0 ) { if ( htmlStart == 0 ) { htmlContent = strstr( buffer, "\r\n\r\n" ); if ( htmlContent != NULL ) { htmlStart = 1; htmlContent += 4; } } else htmlContent = buffer; if( htmlStart ) fprintf( stdout, "%s", htmlContent ); memset( buffer, 0, actionResult ); } if ( actionResult < 0 ) perror( "Error: Not receiving data" ); // clean up free( query ); free( remote ); close( socket ); return 0; } int construct_socket() { int _socket; if ( ( _socket = socket( AF_INET, SOCK_STREAM, 6 ) ) < 0 ) { perror( "Error: Unable to create TCP socket" ); exit( 1 ); } return _socket; } char *get_query(char *host, char *page) { char *query; char *getpage = page; char *tpl = "GET /%s HTTP/1.0\r\nHost: %s\r\nUser-Agent: %s\r\n\r\n"; if ( getpage[0] == '/' ) { getpage = getpage + 1; fprintf( stderr,"Removing leading \"/\", converting %s to %s\n", page, getpage ); } query = (char *)malloc( strlen( host ) + strlen( getpage ) + strlen( USERAGENT ) + strlen( tpl ) - 5 ); sprintf( query, tpl, getpage, host, USERAGENT ); return query; }