-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient_simple.c
More file actions
84 lines (73 loc) · 1.72 KB
/
client_simple.c
File metadata and controls
84 lines (73 loc) · 1.72 KB
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
/*
* client_simple.c: A very, very primitive HTTP client.
*
* To run, try:
* client www.ece.toronto.edu 80 /
* client www.google.ca 80 /
*
* Sends one HTTP request to the specified HTTP server.
* Prints out the HTTP response.
*/
#include "common.h"
/* send an HTTP request for the specified file */
static void
client_send(int fd, char *host, char *filename)
{
char buf[MAXLINE];
/* form and send the HTTP request */
sprintf(buf, "GET %s HTTP/1.0\r\n", filename);
sprintf(buf + strlen(buf), "host: %s\r\n\r\n", host);
Rio_write(fd, buf, strlen(buf));
}
/* read the HTTP response and print it out */
static void
client_print(int fd)
{
struct rio *rio;
char buf[MAXBUF];
int n;
int length = 0;
int length_received = 0;
rio = Rio_init(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);
/* look for certain HTTP tags... */
if (sscanf(buf, "Content-Length: %d ", &length) == 1) {
/* found length tag */
}
}
fflush(stdout);
/* read and display the HTTP body */
do {
n = Rio_readlineb(rio, buf, MAXBUF);
Rio_write(STDOUT_FILENO, buf, n);
length_received += n;
} while (n > 0);
if (length != 0)
assert(length == length_received);
Rio_destroy(rio);
}
int
main(int argc, char *argv[])
{
int i = 1;
char *filename;
int clientfd;
char *host;
int port;
if (argc != 4) {
fprintf(stderr, "Usage: %s host port filename\n", argv[0]);
exit(1);
}
host = argv[i++];
port = atoi(argv[i++]);
filename = argv[i++];
clientfd = open_clientfd(host, port);
client_send(clientfd, host, filename);
client_print(clientfd);
SYS(close(clientfd));
exit(0);
}