-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathwclient.c
92 lines (76 loc) · 2.21 KB
/
wclient.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
//
// client.c: A very, very primitive HTTP client.
//
// To run, try:
// client hostname portnumber filename
//
// Sends one HTTP request to the specified HTTP server.
// Prints out the HTTP response.
//
// 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 "io_helper.h"
#define MAXBUF (8192)
//
// Send an HTTP request for the specified file
//
void client_send(int fd, char *filename) {
char buf[MAXBUF];
char hostname[MAXBUF];
gethostname_or_die(hostname, MAXBUF);
/* Form and send the HTTP request */
sprintf(buf, "GET %s HTTP/1.1\n", filename);
sprintf(buf, "%shost: %s\n\r\n", buf, hostname);
write_or_die(fd, buf, strlen(buf));
}
//
// Read the HTTP response and print it out
//
void client_print(int fd) {
char buf[MAXBUF];
int n;
// Read and display the HTTP Header
n = readline_or_die(fd, buf, MAXBUF);
while (strcmp(buf, "\r\n") && (n > 0)) {
printf("Header: %s", buf);
n = readline_or_die(fd, buf, MAXBUF);
// If you want to look for certain HTTP tags...
// int length = 0;
//if (sscanf(buf, "Content-Length: %d ", &length) == 1) {
// printf("Length = %d\n", length);
//}
}
// Read and display the HTTP Body
n = readline_or_die(fd, buf, MAXBUF);
while (n > 0) {
printf("%s", buf);
n = readline_or_die(fd, 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_client_fd_or_die(host, port);
client_send(clientfd, filename);
client_print(clientfd);
close_or_die(clientfd);
exit(0);
}