-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.c
98 lines (82 loc) · 2.14 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
/*
* client.c: A very, very primitive HTTP client.
*
* To run, try:
* client www.cs.wisc.edu 80 /
*
* Sends one HTTP request to the specified HTTP server.
* Prints out the HTTP response.
*
* CS537: For testing your server, you will want to modify this client.
* For example:
*
* You may want to make this multi-threaded so that you can
* send many requests simultaneously to the server.
*
* You may also want to be able to request different URIs;
* you may want to get more URIs from the command line
* or read the list from a file.
*
* When we test your server, we will be using modifications to this client.
*
*/
#include "cs537.h"
/*
* Send an HTTP request for the specified file
*/
void clientSend(int fd, char *filename)
{
char buf[MAXLINE];
char hostname[MAXLINE];
Gethostname(hostname, MAXLINE);
/* Form and send the HTTP request */
sprintf(buf, "GET %s HTTP/1.1\n", filename);
sprintf(buf, "%shost: %s\n\r\n", buf, hostname);
Rio_writen(fd, buf, strlen(buf));
}
/*
* Read the HTTP response and print it out
*/
void clientPrint(int fd)
{
rio_t rio;
char buf[MAXBUF];
int length = 0;
int n;
Rio_readinitb(&rio, fd);
/* Read and display the HTTP Header */
n = Rio_readlineb(&rio, buf, MAXBUF);
while (strcmp(buf, "\r\n") && (n > 0)) {
printf("Header: %s", buf);
n = Rio_readlineb(&rio, buf, MAXBUF);
/* If you want to look for certain HTTP tags... */
if (sscanf(buf, "Content-Length: %d ", &length) == 1) {
printf("Length = %d\n", length);
}
}
/* Read and display the HTTP Body */
n = Rio_readlineb(&rio, buf, MAXBUF);
while (n > 0) {
printf("%s", buf);
n = Rio_readlineb(&rio, buf, MAXBUF);
}
}
int main(int argc, char *argv[])
{
char *host, *filename;
int port;
int clientfd;
if (argc != 4) {
fprintf(stderr, "Usage: %s <host> <port> <filename>\n", argv[0]);
exit(1);
}
host = argv[1];
port = atoi(argv[2]);
filename = argv[3];
/* Open a single connection to the specified host and port */
clientfd = Open_clientfd(host, port);
clientSend(clientfd, filename);
clientPrint(clientfd);
Close(clientfd);
exit(0);
}