]> git.proxmox.com Git - mirror_frr.git/blob - lib/ipaddr.h
Merge pull request #784 from Jafaral/debpkgfix
[mirror_frr.git] / lib / ipaddr.h
1 /*
2 * IP address structure (for generic IPv4 or IPv6 address)
3 * Copyright (C) 2016, 2017 Cumulus Networks, Inc.
4 *
5 * This file is part of FRR.
6 *
7 * FRR is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2, or (at your option) any
10 * later version.
11 *
12 * FRR is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with FRR; see the file COPYING. If not, write to the Free
19 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 * 02111-1307, USA.
21 */
22
23 #ifndef __IPADDR_H__
24 #define __IPADDR_H__
25
26 #include <zebra.h>
27
28 /*
29 * Generic IP address - union of IPv4 and IPv6 address.
30 */
31 enum ipaddr_type_t
32 {
33 IPADDR_NONE = 0,
34 IPADDR_V4 = 1, /* IPv4 */
35 IPADDR_V6 = 2, /* IPv6 */
36 };
37
38 struct ipaddr
39 {
40 enum ipaddr_type_t ipa_type;
41 union
42 {
43 u_char addr;
44 struct in_addr _v4_addr;
45 struct in6_addr _v6_addr;
46 } ip;
47 #define ipaddr_v4 ip._v4_addr
48 #define ipaddr_v6 ip._v6_addr
49 };
50
51 #define IS_IPADDR_NONE(p) ((p)->ipa_type == IPADDR_NONE)
52 #define IS_IPADDR_V4(p) ((p)->ipa_type == IPADDR_V4)
53 #define IS_IPADDR_V6(p) ((p)->ipa_type == IPADDR_V6)
54
55 #define SET_IPADDR_V4(p) (p)->ipa_type = IPADDR_V4
56 #define SET_IPADDR_V6(p) (p)->ipa_type = IPADDR_V6
57
58 static inline int
59 str2ipaddr (const char *str, struct ipaddr *ip)
60 {
61 int ret;
62
63 memset (ip, 0, sizeof (struct ipaddr));
64
65 ret = inet_pton (AF_INET, str, &ip->ipaddr_v4);
66 if (ret > 0) /* Valid IPv4 address. */
67 {
68 ip->ipa_type = IPADDR_V4;
69 return 0;
70 }
71 ret = inet_pton (AF_INET6, str, &ip->ipaddr_v6);
72 if (ret > 0) /* Valid IPv6 address. */
73 {
74 ip->ipa_type = IPADDR_V6;
75 return 0;
76 }
77
78 return -1;
79 }
80
81 static inline char *
82 ipaddr2str (struct ipaddr *ip, char *buf, int size)
83 {
84 buf[0] = '\0';
85 if (ip)
86 {
87 if (IS_IPADDR_V4(ip))
88 inet_ntop (AF_INET, &ip->ip.addr, buf, size);
89 else if (IS_IPADDR_V6(ip))
90 inet_ntop (AF_INET6, &ip->ip.addr, buf, size);
91 }
92 return buf;
93 }
94 #endif /* __IPADDR_H__ */