#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <windows.h>
#include <errno.h>
void get(char *hostname,int port,char *path, char *fnm)
{
FILE *fp;
int sd,status,len,first,tmp;
char cmd[512],resp[51200],*body;
struct sockaddr local,remote;
struct hostent *hostinfo;
/* create socket */
sd=socket(AF_INET,SOCK_STREAM,0);
if(sd<0) {
printf("Error creating socket: %s\n",strerror(errno));
goto fin;
}
/* bind socket */
local.sa_family=AF_INET;
memset(local.sa_data,0,sizeof(local.sa_data));
status=bind(sd,&local,sizeof(local));
if(status<0) {
printf("Error binding socket: %s\n",strerror(errno));
goto fin;
}
/* lookup host */
hostinfo=gethostbyname(hostname);
if(!hostinfo) {
printf("Error looking up host: %s\n",hostname);
goto fin;
}
/* connect to host */
remote.sa_family=hostinfo->h_addrtype;
memcpy(remote.sa_data+2,hostinfo->h_addr_list[0],hostinfo->h_length);
*((short *)remote.sa_data)=port;
tmp=remote.sa_data[0];
remote.sa_data[0]=remote.sa_data[1];
remote.sa_data[1]=tmp;
status=connect(sd,&remote,sizeof(remote));
if(status!=0) {
printf("Error connecting to host: %s port: %d\n",hostname,port);
goto fin;
}
/* send GET request */
sprintf(cmd,"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n",path,hostname);
status=send(sd,cmd,strlen(cmd),0);
if(status<0) {
printf("Error sending GET request\n");
goto fin;
}
/* read response */
fp = fopen(fnm,"wb");
first = 1;
while ((len=recv(sd,resp,sizeof(resp),0))>0) {
if(first) {
body = strstr(resp,"\r\n\r\n") + 4;
first = 0;
} else {
body = resp;
}
fwrite(body,len-(body-resp),1,fp);
}
fclose(fp);
fin:
closesocket(sd);
return;
}
int main(int argc,char *argv[])
{
WSADATA WSAData;
WSAStartup(0x0101,&WSAData);
get("
www.eksperten.dk",80,"/img/elogo.png","elogo.png");
WSACleanup();
return 0;
}