xref: /freebsd/sbin/ipf/libipf/gethost.c (revision 9768746b)
1 /*	$FreeBSD$	*/
2 
3 /*
4  * Copyright (C) 2012 by Darren Reed.
5  *
6  * See the IPFILTER.LICENCE file for details on licencing.
7  *
8  * $Id$
9  */
10 
11 #include "ipf.h"
12 
13 int
14 gethost(int family, char *name, i6addr_t *hostp)
15 {
16 	struct hostent *h;
17 	struct netent *n;
18 	u_32_t addr;
19 
20 	bzero(hostp, sizeof(*hostp));
21 	if (!strcmp(name, "test.host.dots")) {
22 		if (family == AF_INET) {
23 			hostp->in4.s_addr = htonl(0xfedcba98);
24 		}
25 #ifdef USE_INET6
26 		if (family == AF_INET6) {
27 			hostp->i6[0] = htonl(0xfe80aa55);
28 			hostp->i6[1] = htonl(0x12345678);
29 			hostp->i6[2] = htonl(0x5a5aa5a5);
30 			hostp->i6[3] = htonl(0xfedcba98);
31 		}
32 #endif
33 		return (0);
34 	}
35 
36 	if (!strcmp(name, "<thishost>"))
37 		name = thishost;
38 
39 	if (family == AF_INET) {
40 		h = gethostbyname(name);
41 		if (h != NULL) {
42 			if ((h->h_addr != NULL) &&
43 			    (h->h_length == sizeof(addr))) {
44 				bcopy(h->h_addr, (char *)&addr, sizeof(addr));
45 				hostp->in4.s_addr = addr;
46 				return (0);
47 			}
48 		}
49 
50 		n = getnetbyname(name);
51 		if (n != NULL) {
52 			hostp->in4.s_addr = htonl(n->n_net & 0xffffffff);
53 			return (0);
54 		}
55 	}
56 #ifdef USE_INET6
57 	if (family == AF_INET6) {
58 		struct addrinfo hints, *res;
59 		struct sockaddr_in6 *sin6;
60 
61 		bzero((char *)&hints, sizeof(hints));
62 		hints.ai_family = PF_INET6;
63 
64 		getaddrinfo(name, NULL, &hints, &res);
65 		if (res != NULL) {
66 			sin6 = (struct sockaddr_in6 *)res->ai_addr;
67 			hostp->in6 = sin6->sin6_addr;
68 			freeaddrinfo(res);
69 			return (0);
70 		}
71 	}
72 #endif
73 	return (-1);
74 }
75