HTTPクライアント(ソケット通信)

ソケット通信によりHTTPサーバへアクセスし,指定したページをダウンロードする例題です.

ソースのダウンロード

実行時の引数は以下のようになります。

  Gami[226]%   ./list_57 http://www-cc.ee.tokushima-u.ac.jp/~a-gamyl/Clang/index.html  

 HTTPクライアント (ソケット通信)(list_57.c)
//-----------------------------------------------------------------
// HTTP クライアント (ソケット通信)
// % ./http-client [URL]
//-----------------------------------------------------------------

#include <stdio.h>
#include "http_lib.h"

int main(int argc, char *argv[])
{
    int i,read_size,r_head;
    int s; // ソケットのためのファイルディスクリプタ
    unsigned short port = 0;          // 接続するポート番号
    char host[URL_LEN] = "localhost"; // 接続するホスト名
    char path[URL_LEN] = "/";         // 要求するパス
    char buf[BUFSIZ];

    if(argc != 2) {
        printf("usage: %s URL\n",argv[0]);
        return 0;
    }
    if(split_url(argv[1],host,path,&port))
        return 0;
    
    fprintf(stderr,"%s を取得します。\n\n",argv[1]);
    
    // サーバに接続
    if((s = http_open(host,port)) < 0){
        return 0;
    }
    // サーバに受信要求
    http_request(s,host,path,port);
    // 受信&表示
    r_head = 1;
    while(1){
        read_size = read(s,buf,BUFSIZ);
        if(read_size > 0){
            for(i=0;i<read_size;i++){
                if(r_head == 1){ // ヘッダ部の無視
                    if(!strncmp(buf+i,"\r\n\r\n",4)){
                        i+=4; r_head = 0;
                    }
                } else {
                    if(buf[i] != '\r') write(1,buf+i,1);
                }
            }
        } else break;
    }
    // 後始末
    close(s);
    return 0;
}
inserted by FC2 system