#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define BUF_LEN 256
#define port 80
int main(int argc, char *argv[]){
int s;
struct hostent *servhost;
struct sockaddr_in server;
struct servent *service;
FILE *fp;
char buf[BUF_LEN];
char host[BUF_LEN] = "";
char path[BUF_LEN] = "/";
if ( argc > 1 ){
char host_path[BUF_LEN];
if ( strlen(argv[1]) > BUF_LEN-1 ){
fprintf(stderr, "URL が長すぎます。\n");
return 1;
}
if ( strstr(argv[1], "http://") &&
sscanf(argv[1], "http://%s", host_path) &&
strcmp(argv[1], "http://" ) ){
char *p;
p = strchr(host_path, '/');
if ( p != NULL ){
strcpy(path, p);
*p = '\0';
strcpy(host, host_path);
} else {
strcpy(host, host_path);
}
} else {
fprintf(stderr,"URL は http://host/path の形式で指定してください。\n");
return 1;
}
}
printf("http://%s%s を取得します。\n\n",host, path);
servhost = gethostbyname(host);
if ( servhost == NULL ){
fprintf(stderr, "[%s] から IP アドレスへの変換に失敗しました。\n", host);
return 0;
}
bzero((char *)&server, sizeof(server)); // ゼロクリア
server.sin_family = AF_INET;
bcopy(servhost->h_addr, (char *)&server.sin_addr, servhost->h_length);
if ( port != 0 ){
server.sin_port = htons(port);
} else {
service = getservbyname("http", "tcp");
if ( service != NULL ){
server.sin_port = service->s_port;
} else {
server.sin_port = htons(80);
}
}
if ( ( s = socket(AF_INET, SOCK_STREAM, 0) ) < 0 ){
fprintf(stderr, "\n");
return 1;
}
if ( connect(s, (struct sockaddr *)&server, sizeof(server)) ==
-1 ){
fprintf(stderr, "\n");
return 1;
}
fp = fdopen(s, "r+");
if ( fp == NULL ){
fprintf(stderr, "\n");
return 1;
}
setvbuf(fp, NULL, _IONBF, 0);
fprintf(fp, "GET %s HTTP/1.0\r\n", path);
printf("GET %s HTTP/1.0\r\n", path);
fprintf(fp, "Host: %s:%d\r\n", host, port);
printf("Host: %s:%d\r\n", host, port);
fprintf(fp, "\r\n");
printf("\r\n");
while (1){
if ( fgets(buf, sizeof(buf), fp) == NULL ){
break;
}
printf("%s", buf);
}
fclose(fp);
close(s);
return 0;
}
|