/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#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,int noblock)
{
   int sd,status,len,ix,tmp;
   char cmd[512],resp[51200];
   struct sockaddr local,remote;
   struct hostent *hostinfo;
   time_t t;
   int one = 1;
   /* 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 */
   ix=0;
   if(noblock) {
      status=ioctlsocket(sd, FIONBIO, &one);
      if(status<0) {
         printf("Error setting socket nonblocked: %s\n",strerror(errno));
         goto fin;
      }
      t=time(NULL);
      while (time(NULL)<(t+10)) {
         len=recv(sd,resp+ix,sizeof(resp)-ix-1,0);
         if(len<0) len=0;
         ix = ix + len;
         printf("no blocking read %d bytes\n",len);
         Sleep(1000);
      }
   } else {
      while ((len=recv(sd,resp+ix,sizeof(resp)-ix-1,0))>0) {
         ix = ix + len;
         printf("blocking read %d bytes\n",len);
      }
   }
   resp[ix]='\0';
   /*printf("%s",resp);*/
fin:
   closesocket(sd);
   return;
}

int main(int argc,char *argv[])
{
   WSADATA WSAData;
   WSAStartup(0x0101,&WSAData);
   get("www.dr.dk",80,"/",0);
   get("www.dr.dk",80,"/",1);
   WSACleanup();
}
