I am trying to write code in C which send a HTTP request to the VirusTotal API with no luck. I tried to do this on the base of the following answer:
Simple C example of doing an HTTP POST and consuming the response
I don't know how to phrase my request and how to send the content of the file as expected. Right now my code looks like this:
FILE* file = fopen (fileName , "r");
size_t prev=ftell(file);
fseek(file, 0L, SEEK_END);
size_t len=ftell(file);
fseek(file,prev,SEEK_SET);
char buffer [(int)len];
fread (buffer , sizeof (char), len, file);
int portno = 80;
char *host = "https://www.virustotal.com/vtapi/v2/file/scan";
char *message_fmt = "POST /apikey=%s&command=%s HTTP/1.0\r\n\r\n";
struct hostent *server;
struct sockaddr_in serv_addr;
int sockfd, bytes, sent, received, total;
char message[1024],response[4096];
/* fill in the parameters */
char* apikey = "d973c620d9fbbf8540ea5b034af27c3ce4270f2959a506ca3d3********";
sprintf(message,message_fmt,apikey,file);
printf("Request:\n%s\n",message);
/* create the socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
/* lookup the ip address */
server = gethostbyname(host);
if (server == NULL) {printf("ERROR, no such host"); exit(0);}
/* fill in the structure */
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
/* connect the socket */
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
/* send the request */
total = strlen(message);
sent = 0;
do {
bytes = write(sockfd,message+sent,total-sent);
if (bytes < 0)
error("ERROR writing message to socket");
if (bytes == 0)
break;
sent+=bytes;
} while (sent < total);
/* receive the response */
memset(response,0,sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
bytes = read(sockfd,response+received,total-received);
if (bytes < 0)
error("ERROR reading response from socket");
if (bytes == 0)
break;
received+=bytes;
} while (received < total);
if (received == total)
error("ERROR storing complete response from socket");
/* close the socket */
close(sockfd);
/* process response */
printf("Response:\n%s\n",response);
Thanks.