* -*- C -*- * * gethtml.c - Note: http头结束是\r\n\r\n * 参考 :
* Author : heixia * Created On : Sat Mar 29 01:33:11 2008 * */
#include #include #include #include #include #include #include
#define BUFSIZE 128
int main(int argc,char *argv[ ] ){ char *url,*pHost,host[ BUFSIZE ],GET[ BUFSIZE ]; int sockfd; int len,result; struct sockaddr_in address; struct hostent *hostinfo; struct servent *servinfo; char buffer[ BUFSIZE ],header[ BUFSIZE ]="";
if( argc == 1 ){ fprintf( stderr,"./a.out netaddress.\n." ); exit( 1 ); } else url = argv[ 1 ];
/* * 分离url中的主机地址和相对路径 */
for (pHost = url; *pHost != '/' && *pHost != '\0'; pHost++ ) ; if ( (int)(pHost - url) == strlen(url) ) strcpy(GET, "/"); else strcpy(GET, pHost); *pHost = '\0'; strcpy(host, url); printf("%s\n%s\n", host, GET);
hostinfo = gethostbyname( host ); if( !hostinfo ){ fprintf( stderr,"can't get inof for host: %s\n",host ); exit( 1 ); }
sockfd = socket( AF_INET,SOCK_STREAM,0 );
address.sin_family = AF_INET; address.sin_port = htons( 80 ); address.sin_addr = *( struct in_addr * )*hostinfo->h_addr_list; len = sizeof( address );
strcat( header,"GET " ); strcat( header,GET); strcat( header," " ); strcat( header,"HTTP/1.1\r\n"); strcat( header,"Host: "); strcat( header,host); strcat( header,"\r\nConnection: close\r\n\r\n"); //建立连接 result = connect( sockfd,( struct sockaddr * )&address,len ); if( result == -1 ){ perror( "oops:getdate" ); exit( 1 ); }
write( sockfd,header,strlen( header ) ); while( read( sockfd,buffer,sizeof( buffer )) > 0){ printf( "%s",buffer ); memset( buffer,0,sizeof( buffer ) ); }
close( sockfd ); exit( 0 ); }
|