curl の実行を再現するC言語を作る、--libcurl オプション
curl に libcurl オプションをつけると、C言語のソースが出力される。なにこれ楽しい。
使い方例
次のように --libcurl ファイル名 をオプションにつける.
curl 'https://api.ipify.org?format=json' --libcurl get_global_ip.c
# >{"ip":"103.xxx.1x2.6x"}
するとCのファイルが出力されるので、コンパイルする
gcc get_global_ip.c -o global_ip -lcurl
で、コンパイルされたバイナリを実行する。
./global_ip
# >{"ip":"103.xxx.1x2.6x"}
何だこれ、楽しい。
もしかして、gist / gyazo のアップロード、PHPに定期的に呼び出すなど、定型文のコマンドが作れる。curl 最高
っていうかlibcurlをC言語から各サンプルコードを大量生成出来る。
あ、curl って scp や ftp も対応してたよな・・・ってことは。通信系のプログラミングが超楽に作れるじゃん。
scp 通信するlibcurlC言語ソース生成してみよう
libcurl をssh オプションでインストール
brew install curl --with-ssh2 brew link curl -f
curl -u takuya_1st --key /Users/takuya_1st/.ssh/id_rsa \ -T ~/Desktop/sample scp://my.host.example.com/home/takuya_1st/sample \ --libcurl scp.c
コンパイルする
gcc scp.c -lcurl -L/usr/local/lib
実行
./a.out
おお、接続できた。これって色々と使えそう。
生成されたC言語のソースはこんな感じ
/********* Sample code generated by the curl command line tool **********
* All curl_easy_setopt() options are documented at:
* http://curl.haxx.se/libcurl/c/curl_easy_setopt.html
************************************************************************/
#include <curl/curl.h>
int main(int argc, char *argv[])
{
CURLcode ret;
CURL *hnd;
hnd = curl_easy_init();
curl_easy_setopt(hnd, CURLOPT_URL, "https://api.ipify.org?format=json");
curl_easy_setopt(hnd, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(hnd, CURLOPT_USERAGENT, "curl/7.37.1");
curl_easy_setopt(hnd, CURLOPT_MAXREDIRS, 50L);
curl_easy_setopt(hnd, CURLOPT_TCP_KEEPALIVE, 1L);
/* Here is a list of options the curl code used that cannot get generated
as source easily. You may select to either not use them or implement
them yourself.
CURLOPT_WRITEDATA set to a objectpointer
CURLOPT_WRITEFUNCTION set to a functionpointer
CURLOPT_READDATA set to a objectpointer
CURLOPT_READFUNCTION set to a functionpointer
CURLOPT_SEEKDATA set to a objectpointer
CURLOPT_SEEKFUNCTION set to a functionpointer
CURLOPT_ERRORBUFFER set to a objectpointer
CURLOPT_STDERR set to a objectpointer
CURLOPT_HEADERFUNCTION set to a functionpointer
CURLOPT_HEADERDATA set to a objectpointer
*/
ret = curl_easy_perform(hnd);
curl_easy_cleanup(hnd);
hnd = NULL;
return (int)ret;
}
/**** End of sample code ****/
libcurl-dev のインストール / 2023-09-29 追記
gcc でコンパイルするときに必要なパッケージは、以下のようになる。
sudo apt-get install libcurl4-openssl-dev build-essentials
久しぶりにやろうとしたら、fatal error: curl/curl.h: No such file or directory になって焦った。
昔は sudo apt-get install libcurl-devだったけど。今は変わったみたいね。
libcurl4-gnutls-dev または libcurl4-openssl-dev から選べばいいようです。
参考資料
http://qiita.com/Hiraku/items/dfda2f8a5353b0742271
更新
2023/09/29 libcurl-dev を入れる方法について追記