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