+// Connect to a Citadel on a remote host using a TCP/IP socket
+static int tcp_connectsock(char *host, char *service) {
+ struct in6_addr serveraddr;
+ struct addrinfo hints;
+ struct addrinfo *res = NULL;
+ struct addrinfo *ai = NULL;
+ int rc = (-1);
+ int sock = (-1);
+
+ if ((host == NULL) || IsEmptyStr(host)) {
+ return(-1);
+ }
+ if ((service == NULL) || IsEmptyStr(service)) {
+ return(-1);
+ }
+
+ memset(&hints, 0x00, sizeof(hints));
+ hints.ai_flags = AI_NUMERICSERV;
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+
+ // Handle numeric IPv4 and IPv6 addresses
+ rc = inet_pton(AF_INET, host, &serveraddr);
+ if (rc == 1) { // dotted quad
+ hints.ai_family = AF_INET;
+ hints.ai_flags |= AI_NUMERICHOST;
+ } else {
+ rc = inet_pton(AF_INET6, host, &serveraddr);
+ if (rc == 1) { // IPv6 address
+ hints.ai_family = AF_INET6;
+ hints.ai_flags |= AI_NUMERICHOST;
+ }
+ }
+
+ // Begin the connection process
+ rc = getaddrinfo(host, service, &hints, &res);
+ if (rc != 0) {
+ fprintf(stderr, "ctdlmigrate: %s\n", strerror(errno));
+ return (-1);
+ }
+
+ // Try all available addresses until we connect to one or until we run out.
+ for (ai = res; ai != NULL; ai = ai->ai_next) {
+ sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
+ if (sock < 0) {
+ fprintf(stderr, "ctdlmigrate: %s\n", strerror(errno));
+ return (-1);
+ }
+
+ rc = connect(sock, ai->ai_addr, ai->ai_addrlen);
+ if (rc >= 0) {
+ return (sock); // Connected!
+ }
+ else {
+ fprintf(stderr, "ctdlmigrate: %s\n", strerror(errno));
+ close(sock); // Failed. Close the socket to avoid fd leak!
+ }
+ }
+ return (-1);
+}
+
+
+// Connect to a Citadel on a remote host using a unix domaion socket