-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock_http_client.c
More file actions
88 lines (79 loc) · 1.43 KB
/
block_http_client.c
File metadata and controls
88 lines (79 loc) · 1.43 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
85
86
87
88
/* For sockaddr_in */
#include <netinet/in.h>
/* For socket functions */
#include <sys/socket.h>
/* For gethostbyname */
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
int main(int argc, char **argv)
{
const char query[] =
"GET / HTTP/1.0\r\n"
"Host: www.baidu.com\r\n"
"\r\n";
const char hostname[] = "www.baidu.com";
struct sockaddr_in sin;
struct hostent *h;
const char *cp;
int fd;
ssize_t n_written, remaining;
char buf[1024];
h = gethostbyname(hostname);
if (!h)
{
fprintf(stderr, "Couldn't lookup %s:%s", hostname, hstrerror(h_errno));
return 1;
}
if (h->h_addrtype != AF_INET)
{
fprintf(stderr, "No ipv6 support, sorry.");
return 1;
}
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
{
perror("socket");
return 1;
}
sin.sin_family = AF_INET;
sin.sin_port = htons(80);
sin.sin_addr = *(struct in_addr*)h->h_addr;
if (connect(fd, (struct sockaddr*)&sin, sizeof(sin)))
{
perror("connect");
close(fd);
return 1;
}
cp = query;
remaining = strlen(query);
while(remaining)
{
n_written = send(fd, cp, remaining, 0);
if (n_written <= 0)
{
perror("send");
return 1;
}
remaining -= n_written;
cp += n_written;
}
while(1)
{
ssize_t result = recv(fd, buf, sizeof(buf), 0);
if (result == 0)
{
break;
}
else if (result < 0)
{
perror("recv");
close(fd);
return 1;
}
fwrite(buf, 1, result, stdout);
}
close(fd);
return 0;
}