Corretto titolo della sezione IPC, e iniziato a scrivere funzione generica
[gapil.git] / sources / sockconn.c
diff --git a/sources/sockconn.c b/sources/sockconn.c
new file mode 100644 (file)
index 0000000..c162474
--- /dev/null
@@ -0,0 +1,65 @@
+/* sockconn.c
+ * 
+ * Copyright (C) 2004 Simone Piccardi
+ * 
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful, but
+ * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+/****************************************************************
+ *
+ * Routine sockconn
+ * Return a connected socket given hostname, service, and socket type
+ *
+ * Author: Simone Piccardi
+ * Dec. 2004
+ *
+ * $Id$ 
+ *
+ ****************************************************************/
+#include <arpa/inet.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <errno.h>
+
+int sockconn(char *host, char *serv, int prot, int type) 
+{
+    struct addrinfo hint, *addr;
+    int res;
+    int sock
+    /* initialize hint */
+    memset(&hint, 0, sizeof(hint)); 
+    hint.ai_family = PF_UNSPEC;
+    hint.ai_protocol = prot;
+    hint.ai_socktype = type;
+    res = getaddrinfo(host, serv, &hint, &addr);
+    if (res != 0) {
+       printf("sockconn cannot resolve host %s, service %s,
+                protocol %d: %s\n", host, serv, prot, gai_strerror(res));
+       errno = 0;
+       return -1;
+    }
+    sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
+    if (sock < 0) {
+       perror("sockconn cannot create socket\n");
+       return sock;
+    }
+    res = connect(sock, addr->ai_addr, addr->ai_addrlen);
+    if (res < 0) {
+       perror("sockconn cannot connect socket\n");
+       return res;
+    }
+    freeaddrinfo(addr);
+    return sock;
+}
+