#include #include #include #include #include #include #include #include #include #include #include #include #include "log.h" void die(const char *errstr, ...) { va_list ap; va_start(ap, errstr); vfprintf(stderr, errstr, ap); va_end(ap); exit(1); } // Client connection typedef struct { int fd; } cconnection_t; void* get_in_addr(struct sockaddr *addr) { if (addr->sa_family == AF_INET) { return &((struct sockaddr_in*)addr)->sin_addr; } return &((struct sockaddr_in6*)addr)->sin6_addr; } // Returns error or nullptr char* connect_server(char *hostname, char *port, cconnection_t *connection) { int rv; struct addrinfo hints, *res, *p; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if ((rv = getaddrinfo(hostname, port, &hints, &res)) != 0) { die("error getting address info: %s\n", gai_strerror(rv)); } int fd; char ip_str[INET6_ADDRSTRLEN]; for (p = res; p != nullptr; p = p->ai_next) { if ((fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { close(fd); continue; } inet_ntop(p->ai_family, get_in_addr(p->ai_addr), ip_str, sizeof(ip_str)); if (connect(fd, p->ai_addr, p->ai_addrlen) != 0) { log_warn("Connection to %s:%s unsuccessful. %s", ip_str, port, strerror(errno)); continue; } log_info("Connection to %s successful", ip_str); break; } if (p == nullptr) { ssize_t err_size = 512; char *err = malloc(512); snprintf(err, err_size, "Failed to connect to %s:%s", hostname, port); return err; } freeaddrinfo(res); return nullptr; } int main() { if(nullptr == NULL) return 1; return 0; }