#include /* printf() */ #include /* atoi() */ #include /* we'll use some string funcs, also memset() */ #include /* for variable argument lists */ #include /* sockaddr_in, inet_addr() */ #include /* socket(), connect(), send(), recv() */ #include /* close() */ typedef struct { /* The socket our client will transmit data on */ int sock; /* The server address */ struct sockaddr_in teepeeServerAddr; /* The port we're going to connect on */ unsigned short teepeeServerPort; /* A pointer to char for storing the IP */ char *serverIp; /* A pointer to char for storing the url we're gonna GET */ char *geturl; } HttpConnection; #define RECVBUFSIZE 1024 /* The size alloted to the buffer we're going to use * for the recv() buffer */ #define SENDBUFSIZE 1024 void DieWithError( char *errorMessage ); /* outputs errorMessage and quits */ int HttpGet( HttpConnection *, int bufsize, char *url, ...); int main ( void ) { char recvBuf[RECVBUFSIZE]; /* buffer used for storing recv() messages */ unsigned short bytesRcvd = 0; /* used for indexing recvBuf after recv() */ int got = 0; HttpConnection teepeecon, *teepee = &teepeecon; teepee->serverIp = "80.237.130.133"; teepee->geturl = "/"; teepee->teepeeServerPort = 80; if ((teepee->sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) DieWithError("Error: socket() failed."); memset(&(teepee->teepeeServerAddr), 0, sizeof(teepee->teepeeServerAddr)); teepee->teepeeServerAddr.sin_family = AF_INET; teepee->teepeeServerAddr.sin_addr.s_addr = inet_addr(teepee->serverIp); teepee->teepeeServerAddr.sin_port = htons(teepee->teepeeServerPort); if (connect(teepee->sock, (struct sockaddr *) &(teepee->teepeeServerAddr), sizeof(teepee->teepeeServerAddr)) < 0) DieWithError("Error: connect() failed."); HttpGet( teepee, SENDBUFSIZE, "GET http://%s%s HTTP/1.0\n\n", teepee->serverIp, teepee->geturl); while ( 1 ) { if ((bytesRcvd = recv(teepee->sock, recvBuf, RECVBUFSIZE-1, 0)) <= 0) DieWithError("recv failed\n"); recvBuf[bytesRcvd] = '\0'; printf(recvBuf); } return 0; } /* DieWithError */ void DieWithError( char *errorMsg ) { perror(errorMsg); exit(1); } int HttpGet( HttpConnection * teepeecon, int bufsize, char *url, ...) { va_list args; char *buffer = malloc((size_t)bufsize); unsigned int bufLen; int retn = 0; va_start(args, url); vsnprintf(buffer, bufsize, url, args); va_end(args); bufLen = strlen(buffer); if (send(teepeecon->sock, buffer, bufLen, 0) == bufLen) goto out; else { retn = -1; goto out; } out: free(buffer); return retn; }