Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
HTTPクライアント
// httpclient.c
// HTTPクライアント
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
int ret;
int sock;
char *url;
char *port;
char *page;
char buf[BUFSIZ];
char host[NI_MAXHOST];
char serv[NI_MAXSERV];
struct addrinfo hints;
struct addrinfo *res;
// 引数チェック
if (argc <= 3) {
printf("%s: no input [url] [port] [page]\n", argv[0]);
exit(EXIT_FAILURE);
}
// サーバのURLとPORT番号を引数から渡す
url = argv[1];
port = argv[2];
page = argv[3];
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_INET;
// URL, PORT番号からソケットアドレス構造体を生成
ret = getaddrinfo(url, port, &hints, &res);
if (ret != 0) {
printf("Error: getaddrinfo: %s\n", gai_strerror(ret));
exit(EXIT_FAILURE);
}
// ソケットアドレス構造体からIPアドレスとPORT番号を求める
ret = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof(host),
serv, sizeof(serv),
NI_NUMERICHOST | NI_NUMERICSERV);
if (ret != 0) {
printf("Error: getnameinfo: %s\n", gai_strerror(ret));
freeaddrinfo(res);
exit(EXIT_FAILURE);
}
printf("addr=%s\n", host);
printf("port=%s\n", serv);
// ソケットを生成
sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (sock == -1) {
printf("Error: socket() %s\n", strerror(errno));
freeaddrinfo(res);
exit(EXIT_FAILURE);
}
// サーバに接続
ret = connect(sock, res->ai_addr, res->ai_addrlen);
if (ret == -1) {
printf("Error: connect() %s\n", strerror(errno));
freeaddrinfo(res);
close(sock);
exit(EXIT_FAILURE);
}
freeaddrinfo(res);
// サーバにメッセージを要求(リクエスト)を送信
memset(buf, 0, sizeof(buf));
snprintf(buf, sizeof(buf), "GET %s /HTTP/1.1\r\nHOST:%s\r\n\r\n", page, url);
printf("len=%d, buf=\n%s\n", (int)strlen(buf), buf);
ret = write(sock, buf, strlen(buf));
if (ret == -1) {
printf("Error: write() %s\n", strerror(errno));
close(sock);
exit(EXIT_FAILURE);
}
// サーバの応答(レスポンス)を表示
while (ret > 0) {
memset(buf, 0, sizeof(buf));
ret = read(sock, buf, sizeof(buf));
if (ret == -1) {
printf("Error: read() %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (ret > 0) printf(buf);
}
printf("\n");
close(sock);
exit(EXIT_SUCCESS);
}
# Makefile
httpclient: httpclient.c
gcc -o httpclient httpclient.c
clean:
rm -f httpclient
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment