3 * Copyright (C) 2004 Simone Piccardi
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or (at
8 * your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 /****************************************************************
22 * Return a binded socket given hostname, service, and socket type
24 * Author: Simone Piccardi
29 ****************************************************************/
30 #include <arpa/inet.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
38 int sockbind(char *host, char *serv, int prot, int type)
40 struct addrinfo hint, *addr;
43 /* initialize hint structure */
44 memset(&hint, 0, sizeof(struct addrinfo));
45 hint.ai_flags = AI_PASSIVE; /* address for binding */
46 hint.ai_family = PF_UNSPEC; /* generic address (IPv4 or IPv6) */
47 hint.ai_protocol = prot; /* protocol */
48 hint.ai_socktype = type; /* socket type */
49 res = getaddrinfo(host, serv, &hint, &addr); /* calling getaddrinfo */
50 if (res != 0) { /* on error exit */
51 printf("sockbind cannot resolve host %s, service %s, ", host, serv);
52 printf("protocol %d: %s\n", prot, gai_strerror(res));
56 sock = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
58 printf("sockconn cannot create socket\n");
61 /* connect the socket */
62 res = bind(sock, addr->ai_addr, addr->ai_addrlen);
64 printf("sockconn cannot bind socket\n");
67 freeaddrinfo(addr); /* done, release memory */