codice:
#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include <string.h>
bool scarica(char *fileremoto,char *filelocale,char *host,char modalita);
int main(int argc, char *argv[]){
scarica("/forum2/","a.txt","www.mamo139.altervista.org",'1');
scarica("/files/4ce85b10a5de4f47ea02d653021d0b42/","a.txt","www785.megavideo.com",'1');
getchar();
}
bool scarica(char *fileremoto,char *filelocale,char *host,char modalita){
FILE *fo;
struct sockaddr_in sock; //la struttura per il socket
struct hostent ip; //la struttura per l'indirizzo
bool header = true;
bool invio = false;
char ultimo_carattere = '\0';
char msg_response[] = "\0";
char modo[4];
int s;
//messaggio per il server...
char msg_enter[600] = "GET ";
char protocollo[] = " HTTP/1.1\n";
char protocollo2[] = "Host: ";
char protocollo3[] = "\n";
char dettagli1[] = "Keep-Alive: 300\n";
char dettagli2[] = "Connection: keep-alive";
strcat(msg_enter,fileremoto);
strcat(msg_enter,protocollo);
strcat(msg_enter,protocollo2);
strcat(msg_enter,host);
strcat(msg_enter,protocollo3);
//strcat(msg_enter,dettagli1); //header
//strcat(msg_enter,dettagli2);
strcat(msg_enter,"\n\n");
strcpy(modo,(modalita == '1' ? "w+b" : "w"));
fo=fopen(filelocale,modo); //creazione file
//********* connessione *********//
WORD wVersion;
WSADATA wsaData;
wVersion = MAKEWORD(2, 2);
WSAStartup(wVersion, &wsaData); //winsock startup
s = socket(AF_INET, SOCK_STREAM, 0);
ip = *(gethostbyname(host)); //indirizzo
memcpy(&sock.sin_addr, ip.h_addr, ip.h_length); //copia l'indirizzo nella struttura socket
sock.sin_family = AF_INET;
sock.sin_port = htons(80); //porta
connect(s, (struct sockaddr *)&sock, sizeof(sock)); //associa al socket s la struttura socket
if (!s) {
printf("Connessione non riuscita!!");
getchar();
return false;
}
printf("Inviato al server:\n\n%s\n", msg_enter);
send(s, msg_enter, strlen(msg_enter) + 1, 0); //invia dati
printf("Download in corso...\n\n");
while(recv(s, msg_response, 1, 0) != 0) {
// se sono finiti gli header stampa nel file
if (!header) fprintf(fo,"%c",msg_response[0]);
else printf("%c",msg_response[0]);
// se l'ultimo carattere è uguale a \r, quello attuale è uguale a \n
// e prima c'era già stato un invio (invio==true), mette header=false
if (ultimo_carattere == 13 && msg_response[0] == 10 && invio==true) header=false;
// ulteriore controllo sugli header
((ultimo_carattere == 13 && msg_response[0] == 10) || (ultimo_carattere==10 && invio))?invio=true:invio=false;
// memorizza l'ultimo carattere
ultimo_carattere = msg_response[0];
//fprintf(fo,"%c",msg_response[0]);
}
printf("File Ricevuto\n");
//operazioni di chiusura!
shutdown(s, 2);
closesocket(s);
WSACleanup();
fclose(fo);
return true;
}