#define _POSIX_C_SOURCE 200112L #include #include #include #include #include #include int open_tcp_connection(char *host, int port) { int sock, rv; struct addrinfo hint = { 0 }; struct addrinfo *addr; hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; rv = getaddrinfo(host, NULL, &hint, &addr); if (rv != 0) { perror(gai_strerror(rv)); return -1; } ((struct sockaddr_in *)addr->ai_addr)->sin_port = htons(port); sock = socket(PF_INET, SOCK_STREAM, 0); if (sock != -1) { if (connect(sock, addr->ai_addr, addr->ai_addrlen) == -1) { perror("can't connect"); close(sock); sock = -1; } } freeaddrinfo(addr); return sock; } #if 0 int main(int ac, char **av) { int socket; char *req = "GET / HTTP/1.1\r\nHost: granicus.if.org\r\nConnection: close\r\n\r\n"; ssize_t bytes; char buffer[1024]; socket = open_tcp_connection(av[1], 80); write(socket, req, strlen(req)); while ((bytes = read(socket, buffer, sizeof buffer)) > 0) { write(1, buffer, bytes); } close(socket); return 0; } #endif