-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.c
101 lines (81 loc) · 2.44 KB
/
client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include "csapp.h"
#define VERSION " HTTP/1.0\r\n"
char *allcaps(char *str);
void genheader(char *host, char *header);
void genrequest(char *request, char *method, char *uri);
int main(int argc, char **argv)
{
int clientfd, port;
char *host;
char buffer[1024];
char buf[MAXLINE], method[MAXLINE], uri[MAXLINE], requesthdr[MAXLINE];
char version[MAXLINE];
//int bufsize;
rio_t rio;
FILE *file;
if(argc!=3){
fprintf(stderr, "usage: %s <host> <port>\n", argv[0]);
exit(0);
}
host=argv[1];
port=atoi(argv[2]);
/* generate the request header for this host */
genheader(host,requesthdr);
clientfd = Open_clientfd(host, port);
Rio_readinitb(&rio, clientfd);
while(Fgets(buf, MAXLINE, stdin)!=NULL){
sscanf(buf ,"%s %s %s", method, uri, version);
if(!strcasecmp(method, "GET")){
genrequest(buf,"GET",uri); /* generate request into buf */
strcat(buf, requesthdr); /* concatenate header to buf */
file = Fopen(uri+1,"w");
/* send request+header to host */
Rio_writen(clientfd, buf, strlen(buf));
/* Read the server response header */
do{
Rio_readlineb(&rio,buf,MAXLINE);
printf("%s\n",buf);
}while(strcmp(buf,"\r\n"));
printf("end of server response header\n");
while(Rio_readlineb(&rio,buf,MAXLINE)){
Fputs(buf,file);
}
//printf("wrote to file: %s\n",uri);
Fclose(file);
}
}
/*
while(Fgets(buf, MAXLINE, stdin)!=NULL){
Rio_writen(clientfd, buf, strlen(buf));
Rio_readlineb(&rio, buf, MAXLINE);
Fputs(buf, stdout);
}*/
Close(clientfd);
exit(0);
}
/* allcaps - returns str with all letters capitalized */
char *allcaps(char *str)
{
int i=0;
while(str[i]){
putchar(toupper(str[i]));
i++;
}
return str;
}
/* genheader - compiles a HTTP request header from host name */
void genheader(char *host,char *header){
strcpy(header,"Host: ");
strcat(header,host);
strcat(header,"\r\n\r\n");
}
void genrequest(char *request, char *method, char *uri){
/* create request string */
strcpy(request,"GET");
if (uri[strlen(uri)-1] == '/')
strcat(uri, "index.html");
strcat(request," ");
strcat(request, uri);
strcat(request, VERSION);
printf("%s",request);
}