1 /*
2 * Copyright (C) 2025-2025 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "nstackx_inet.h"
17
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
21
22 #define IPV4_LOOP_IP "127.0.0.1"
23 #define IPV6_LOOP_IP "::1"
24 #define INET_IPV6_LEN 16
25
InetGetAfType(const char * ipStr,union InetAddr * addr)26 uint8_t InetGetAfType(const char *ipStr, union InetAddr *addr)
27 {
28 if (inet_pton(AF_INET, ipStr, &addr->in) > 0) {
29 return AF_INET;
30 }
31 if (inet_pton(AF_INET6, ipStr, &addr->in6) > 0) {
32 return AF_INET6;
33 }
34
35 return AF_ERROR;
36 }
37
Inet6Equal(const union InetAddr * a,const union InetAddr * b)38 static inline bool Inet6Equal(const union InetAddr *a, const union InetAddr *b)
39 {
40 return (memcmp(a->in6.s6_addr, b->in6.s6_addr, INET_IPV6_LEN) == 0);
41 }
42
InetAddrZero(union InetAddr * ip)43 static void InetAddrZero(union InetAddr *ip)
44 {
45 int i;
46 for (i = 0; i < (int)sizeof(struct in6_addr); i++) {
47 ip->in6.s6_addr[i] = 0;
48 }
49 }
50
InetEqual(uint8_t af,const union InetAddr * a,const union InetAddr * b)51 bool InetEqual(uint8_t af, const union InetAddr *a, const union InetAddr *b)
52 {
53 if (af == AF_INET) {
54 return (a->in.s_addr == b->in.s_addr);
55 }
56
57 return Inet6Equal(a, b);
58 }
59
InetEqualZero(uint8_t af,const union InetAddr * a)60 bool InetEqualZero(uint8_t af, const union InetAddr *a)
61 {
62 union InetAddr zero;
63 InetAddrZero(&zero);
64 return InetEqual(af, a, &zero);
65 }
66
InetEqualNone(uint8_t af,const union InetAddr * a)67 bool InetEqualNone(uint8_t af, const union InetAddr *a)
68 {
69 int i;
70 union InetAddr none;
71
72 for (i = 0; i < (int)sizeof(struct in6_addr); i++) {
73 none.in6.s6_addr[i] = 0xff; // INADDR_NONE 0xff
74 }
75
76 return InetEqual(af, a, &none);
77 }
78
InetEqualLoop(uint8_t af,const char * ip)79 bool InetEqualLoop(uint8_t af, const char *ip)
80 {
81 const char *loopIp = af == AF_INET ? IPV4_LOOP_IP : IPV6_LOOP_IP;
82 return (strlen(ip) == strlen(loopIp) && strcmp(ip, loopIp) == 0);
83 }
84 #ifdef __cplusplus
85 }
86 #endif