[[Net001]]

* 単純な client program の例 [#a19edd10]
TCP接続による client program の概要を見るために、例題を作ってみる。

以下に示す例は、指定された host port の Web server に接続して、その start page の内容を取得するものである。host と port は command line で与えられるものとし、port が省略された時は(Web server の default port である)80 を使う。
以下に示す例は、指定された host port の Web server (http server) に接続して、その start page の内容を取得するものである。host と port は command line で与えられるものとし、port が省略された時は(http service の default port である)80 を使う。

Program の流れとしては、与えられた host port に接続し、成功したら、http request message
 GET / HTTP/1.0<CR><LF>
 <CR><LF>

を送る。Web server からは内容(文字列)が送られ、全部送り終わると server から接続を切る。従って、client 側は読めなくなるまで読み続ければよい。
を送る。Web server からは内容(文字列)が送られ、全部送り終わると server から接続を切る。従って、client 側は読めなくなるまで(recv 関数が 0 または負(負は error))を返すまで)読みつづければよい。

 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netdb.h>
 #include <unistd.h>
 #include <errno.h>
 extern int errno;
 
 #define MY_BUFSIZE 1024
 static char buf[MY_BUFSIZE];
 
 int main(int argc, char* argv[])
 {
 	struct sockaddr_in saddr;
 	struct sockaddr_in* resaddr;
 	struct addrinfo hints;
 	struct addrinfo* res;
 	int sd;
 	int err;
 	int port;
 	const char* host;
 	size_t nrecv;
 	size_t n;
 
 	/* Check the command line */
 	if((argc != 2) && (argc != 3))
 	{
 		fprintf(stderr, "Usage: %s host [port]\n", argv[0]);
 		return (-1);
 	}
 
 	/* Set the hostname and port number */
 	res = 0;
 	port = 80;
 	host = argv[1];
 	if(argc == 3)
 	{
 		port = atoi(argv[2]);
 		if(port <= 0)
 		{
 			fprintf(stderr, "Illegal port number (%d)\n", port);
 			return (-1);
 		}
 	}
 
 	/* Get the address */
 	memset(&saddr, 0, sizeof(saddr));
 	memset(&hints, 0, sizeof(hints));
 
 	hints.ai_family = AF_INET;
 	hints.ai_socktype = 0;
 	hints.ai_protocol = 0;
 	if((err = getaddrinfo(host, 0, &hints, &res)) != 0)
 	{
 		return err;
 	}
 	resaddr = (struct sockaddr_in*)res->ai_addr;
 	saddr.sin_family = AF_INET;
 	saddr.sin_port = htons((u_short)port);
 	saddr.sin_addr = resaddr->sin_addr;
 	freeaddrinfo(res);
 
 	/* Create socket */
 	if((sd = socket( PF_INET, SOCK_STREAM, 0)) == -1)
 		return errno;
 
 	/* Connect to the host */
 	if(connect(sd, (const struct sockaddr*)&saddr, sizeof(saddr)) == -1)
 		return errno;
 
 	/* Send the http request */
 	send(sd, "GET / HTTP/1.0\r\n\r\n", 18, 0);
 
 	/* Receive until connection closed */
 	while((nrecv = recv(sd, buf, MY_BUFSIZE, 0)) > 0)
 	{
 		for(n = 0; n < nrecv; n++)
 			fputc((int)buf[n], stdout);
 	}
 
 	/* Close our socket */
 	close(sd);
 	return 0;
 }

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS