Home | History | Annotate | Download | only in lib
      1 /*
      2  * Copyright (c) 2014 Oracle and/or its affiliates. All Rights Reserved.
      3  *
      4  * This program is free software; you can redistribute it and/or
      5  * modify it under the terms of the GNU General Public License as
      6  * published by the Free Software Foundation; either version 2 of
      7  * the License, or (at your option) any later version.
      8  *
      9  * This program is distributed in the hope that it would be useful,
     10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     12  * GNU General Public License for more details.
     13  *
     14  * You should have received a copy of the GNU General Public License
     15  * along with this program; if not, write the Free Software Foundation,
     16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     17  */
     18 
     19 #include <sys/types.h>
     20 #include <sys/socket.h>
     21 #include <netinet/ip.h>
     22 #include <string.h>
     23 #include <unistd.h>
     24 #include <errno.h>
     25 
     26 int bound_socket(int domain, int type)
     27 {
     28 	int sock;
     29 	struct sockaddr_storage addr;
     30 	struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr;
     31 	struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr;
     32 	socklen_t slen;
     33 
     34 	switch (domain) {
     35 	case AF_INET:
     36 		addr4->sin_family = AF_INET;
     37 		addr4->sin_port = 0;
     38 		addr4->sin_addr.s_addr = INADDR_ANY;
     39 		slen = sizeof(*addr4);
     40 		break;
     41 
     42 	case AF_INET6:
     43 		addr6->sin6_family = AF_INET6;
     44 		addr6->sin6_port = 0;
     45 		addr6->sin6_addr = in6addr_any;
     46 		slen = sizeof(*addr6);
     47 		break;
     48 
     49 	default:
     50 		errno = EAFNOSUPPORT;
     51 		return -1;
     52 	}
     53 
     54 	if ((type != SOCK_STREAM) && (type != SOCK_DGRAM)) {
     55 		errno = EINVAL;
     56 		return -1;
     57 	}
     58 
     59 	sock = socket(domain, type, 0);
     60 	if (sock < 0)
     61 		return -1;
     62 
     63 	if (bind(sock, (struct sockaddr *)&addr, slen) < 0) {
     64 		close(sock);
     65 		return -1;
     66 	}
     67 
     68 	return sock;
     69 }
     70