1

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.

Community
  • 1
  • 1
  • You picked up the erroneous code from "Simple C example..." Working code is also available in that post. – dnarsay Apr 05 '16 at 20:12
  • `char *host = "https://www.virustotal.com/vtapi/v2/file/scan";` — this is a URL, not a host name. Did you mean `www.virustotal.com`? – r3mainer Apr 05 '16 at 20:14

1 Answers1

0

To work with HTTPS you'll need to either implement TLS yourself, or use a library like curl to do this.

You might want to have a look at the VirusTotal implementation of the API in C at https://github.com/VirusTotal/c-vtapi

karl
  • 307
  • 1
  • 11