Last active
July 12, 2021 16:38
-
-
Save kYroL01/b92fa0d7664b92a17575227239c17076 to your computer and use it in GitHub Desktop.
curl_pcap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Take the URL of remote pcap from command line and download the file to disk | |
* It check if the extension is allowed (pcap-cap-pcapng) | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <curl/curl.h> | |
#define FILENAME_LEN 1000 | |
size_t write_data_cb(void *ptr, size_t size, size_t nmemb, FILE *stream) { | |
size_t written = fwrite(ptr, size, nmemb, stream); | |
return written; | |
} | |
int check_extension(char *url, int len, char *ext) { | |
if(url == NULL || len == 0) | |
return -1; | |
if(strstr(url, "pcap")) | |
memcpy(ext, "pcap", 4); | |
else if(strstr(url, "cap")) | |
memcpy(ext, "cap", 3); | |
else if(strstr(url, "pcapng")) | |
memcpy(ext, "pcapng", 6); | |
else | |
return -1; | |
return 0; | |
} | |
/* MAIN */ | |
int main(int argc, char *argv[]) { | |
CURL *curl; | |
CURLcode res; | |
FILE *fp; | |
char filename[FILENAME_LEN] = {0}, ext[5] = {0}; | |
int ret, len = 0; | |
/* NOTE: argv[0] is the program name */ | |
char *url = argv[1]; | |
len = strlen(url); | |
/* check extension (pcap-cap-pcang) */ | |
ret = check_extension(url, len, ext); | |
if(ret == -1) { | |
fprintf(stderr, "Extension not allowed\n"); | |
exit(1); | |
} | |
/* give new name base on time */ | |
time_t t = time(NULL); | |
struct tm tm = *localtime(&t); | |
snprintf(filename, FILENAME_LEN, "%d-%02d-%02d-%02d:%02d:%02d.%s", | |
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, ext); | |
/* INIT CURL */ | |
curl = curl_easy_init(); | |
if(curl) { | |
fp = fopen(filename, "wb"); | |
if(fp == NULL) { | |
fprintf(stderr, "Cannot open file\n"); | |
exit(1); | |
} | |
/* SETOPT */ | |
curl_easy_setopt(curl, CURLOPT_URL, url); | |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_cb); | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); | |
res = curl_easy_perform(curl); | |
if(res != 0) { | |
fprintf(stderr, "error on curl_easy_perform function\n"); | |
exit(1); | |
} | |
/* CLEANUP */ | |
curl_easy_cleanup(curl); | |
fclose(fp); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment