xref: /netbsd-src/external/bsd/ntp/dist/tests/libntp/sockaddrtest.c (revision 181254a7b1bdde6873432bffef2d2decc4b5c22f)
1 /*	$NetBSD: sockaddrtest.c,v 1.2 2020/05/25 20:47:36 christos Exp $	*/
2 
3 
4 #include "config.h"
5 #include "ntp.h"
6 #include "ntp_stdlib.h"
7 #include "sockaddrtest.h"
8 
9 sockaddr_u
10 CreateSockaddr4(const char* address, unsigned int port) {
11 	sockaddr_u s;
12 	s.sa4.sin_family = AF_INET;
13 	s.sa4.sin_addr.s_addr = inet_addr(address);
14 	SET_PORT(&s, port);
15 
16 	return s;
17 }
18 
19 
20 int
21 IsEqual(const sockaddr_u expected, const sockaddr_u actual) {
22 	struct in_addr in;
23 	struct in6_addr in6;
24 
25 	if (expected.sa.sa_family != actual.sa.sa_family) {
26 		printf("Expected sa_family: %d but got: %d", expected.sa.sa_family, actual.sa.sa_family);
27 		return FALSE;
28 	}
29 
30 	if (actual.sa.sa_family == AF_INET) { // IPv4
31 		if (expected.sa4.sin_port == actual.sa4.sin_port &&
32 			memcmp(&expected.sa4.sin_addr, &actual.sa4.sin_addr,
33 				   sizeof( in )) == 0) {
34 			return TRUE;
35 		} else {
36 			char buf[4][32];
37 			strlcpy(buf[0], inet_ntoa(expected.sa4.sin_addr), sizeof(buf[0]));
38 			strlcpy(buf[1], socktoa(&expected)              , sizeof(buf[1]));
39 			strlcpy(buf[2], inet_ntoa(actual.sa4.sin_addr)  , sizeof(buf[2]));
40 			strlcpy(buf[3], socktoa(&actual)                , sizeof(buf[3]));
41 			printf("IPv4 comparision failed, expected: %s(%s) but was: %s(%s)",
42 			       buf[0], buf[1], buf[2], buf[3]);
43 			return FALSE;
44 		}
45 	} else if (actual.sa.sa_family == AF_INET6) { //IPv6
46 		if (expected.sa6.sin6_port == actual.sa6.sin6_port &&
47 			memcmp(&expected.sa6.sin6_addr, &actual.sa6.sin6_addr,
48 				   sizeof(in6)) == 0) {
49 			return TRUE;
50 		} else {
51 			printf("IPv6 comparision failed");
52 			return FALSE;
53 		}
54 	} else { // Unknown family
55 		printf("Unknown sa_family: %d",actual.sa.sa_family);
56 		return FALSE;
57 	}
58 }
59 
60