Hente kode:
#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,tmp;
char cmd[512],resp[51200],*p,seg[1024];
struct sockaddr local,remote;
struct hostent *hostinfo;
time_t t;
/* 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\n\r\n",path,hostname);
status=send(sd,cmd,strlen(cmd),0);
if(status<0) {
printf("Error sending POST request\n");
goto fin;
}
/* read response */
fp = fopen(fnm,"wb");
len=recv(sd,resp,sizeof(resp),0);
p = strstr(resp,"\r\n\r\n") + 4;
fwrite(p,1,len-(p-resp),fp);
while ((len=recv(sd,resp,sizeof(resp),0))>0) {
fwrite(resp,1,len,fp);
}
fclose(fp);
fin:
closesocket(sd);
return;
}
int main(int argc,char *argv[])
{
WSADATA WSAData;
WSAStartup(0x0101,&WSAData);
get("
www.domain.dk",80,"/dir/billede.jpg","billede.jpg");
WSACleanup();
return 0;
}