c - VIrusTotal API 的 C 语言短语 HTTP 请求

标签 c http

我正在尝试用 C 编写代码,向 VirusTotal API 发送 HTTP 请求,但没有成功。我尝试根据以下答案执行此操作:

Simple C example of doing an HTTP POST and consuming the response

我不知道如何表达我的请求以及如何按预期发送文件内容。现在我的代码如下所示:

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);

谢谢。

最佳答案

要使用 HTTPS,您需要自己实现 TLS,或者使用类似 curl 的库做这个。

您可能想在 https://github.com/VirusTotal/c-vtapi 查看 API 的 VirusTotal 实现。

关于c - VIrusTotal API 的 C 语言短语 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36435198/

相关文章:

javascript - Safari 中 Express 服务器响应数据中的 HTTP header

c - C编程输出平均值

c - 在 C 中,如何在创建线程时将变量传递给 Pthreads 中的函数?

java - 我们可以使用http代码422(不可处理的实体)进行Get操作吗?

javascript - 用 C 在服务器上处理 javascript XMLHttpRequest

html - 在单个 HTTP 响应中捆绑页面资源,例如图像

javascript - 如何解析http头的第一行?

c - 如何测试 strdup() 是否可用?

c - 这是 C 中的双重释放吗?

c++ - 如何在 makefile 指令中包含 C 和 C++ 文件