xref: /netbsd-src/external/bsd/ntp/dist/tests/libntp/sockaddrtest.c (revision 50c1bace9687b37ab860a3ac85b157d33cb3f3d6)
1 /*	$NetBSD: sockaddrtest.c,v 1.3 2022/10/09 21:41:04 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
CreateSockaddr4(const char * address,unsigned int port)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
IsEqual(const sockaddr_u expected,const sockaddr_u actual)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 		    && expected.sa6.sin6_scope_id == actual.sa6.sin6_scope_id
48 		    && memcmp(&expected.sa6.sin6_addr, &actual.sa6.sin6_addr,
49 			      sizeof(in6)) == 0) {
50 			return TRUE;
51 		} else {
52 			printf("IPv6 comparision failed");
53 			return FALSE;
54 		}
55 	} else { // Unknown family
56 		printf("Unknown sa_family: %d",actual.sa.sa_family);
57 		return FALSE;
58 	}
59 }
60 
61