1 #define _POSIX_C_SOURCE 200112L
2 #include <sys/socket.h>
9 int open_tcp_connection(char *host, int port) {
11 struct addrinfo hint = { 0 };
12 struct addrinfo *addr;
14 hint.ai_family = AF_INET;
15 hint.ai_socktype = SOCK_STREAM;
17 rv = getaddrinfo(host, NULL, &hint, &addr);
19 perror(gai_strerror(rv));
23 ((struct sockaddr_in *)addr->ai_addr)->sin_port = htons(port);
25 sock = socket(PF_INET, SOCK_STREAM, 0);
27 if (connect(sock, addr->ai_addr, addr->ai_addrlen) == -1) {
28 perror("can't connect");
38 int main(int ac, char **av) {
40 char *req = "GET / HTTP/1.1\r\nHost: granicus.if.org\r\nConnection: close\r\n\r\n";
44 socket = open_tcp_connection(av[1], 80);
45 write(socket, req, strlen(req));
46 while ((bytes = read(socket, buffer, sizeof buffer)) > 0) {
47 write(1, buffer, bytes);