1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2008-2011 Lennart Poettering
7 Copyright 2014 Tom Gundersen
9 systemd is free software; you can redistribute it and/or modify it
10 under the terms of the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 2.1 of the License, or
12 (at your option) any later version.
14 systemd is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
19 You should have received a copy of the GNU Lesser General Public License
20 along with systemd; If not, see <http://www.gnu.org/licenses/>.
24 #include "rtnl-util.h"
26 #include "local-addresses.h"
28 static int address_compare(const void *_a
, const void *_b
) {
29 const struct local_address
*a
= _a
, *b
= _b
;
31 /* Order lowest scope first, IPv4 before IPv6, lowest interface index first */
33 if (a
->scope
< b
->scope
)
35 if (a
->scope
> b
->scope
)
38 if (a
->family
== AF_INET
&& b
->family
== AF_INET6
)
40 if (a
->family
== AF_INET6
&& b
->family
== AF_INET
)
43 if (a
->ifindex
< b
->ifindex
)
45 if (a
->ifindex
> b
->ifindex
)
51 int local_addresses(sd_rtnl
*context
, int ifindex
, struct local_address
**ret
) {
52 _cleanup_rtnl_message_unref_ sd_rtnl_message
*req
= NULL
, *reply
= NULL
;
53 _cleanup_rtnl_unref_ sd_rtnl
*rtnl
= NULL
;
54 _cleanup_free_
struct local_address
*list
= NULL
;
55 size_t n_list
= 0, n_allocated
= 0;
62 rtnl
= sd_rtnl_ref(context
);
64 r
= sd_rtnl_open(&rtnl
, 0);
69 r
= sd_rtnl_message_new_addr(rtnl
, &req
, RTM_GETADDR
, 0, AF_UNSPEC
);
73 r
= sd_rtnl_call(rtnl
, req
, 0, &reply
);
77 for (m
= reply
; m
; m
= sd_rtnl_message_next(m
)) {
78 struct local_address
*a
;
83 r
= sd_rtnl_message_get_errno(m
);
87 r
= sd_rtnl_message_get_type(m
, &type
);
91 if (type
!= RTM_NEWADDR
)
94 r
= sd_rtnl_message_addr_get_ifindex(m
, &ifi
);
98 if (ifindex
!= 0 && ifi
!= ifindex
)
101 r
= sd_rtnl_message_addr_get_flags(m
, &flags
);
105 if (flags
& IFA_F_DEPRECATED
)
108 if (!GREEDY_REALLOC(list
, n_allocated
, n_list
+1))
113 r
= sd_rtnl_message_addr_get_scope(m
, &a
->scope
);
117 if (ifindex
== 0 && (a
->scope
== RT_SCOPE_HOST
|| a
->scope
== RT_SCOPE_NOWHERE
))
120 r
= sd_rtnl_message_addr_get_family(m
, &a
->family
);
127 r
= sd_rtnl_message_read_in_addr(m
, IFA_LOCAL
, &a
->address
.in
);
129 r
= sd_rtnl_message_read_in_addr(m
, IFA_ADDRESS
, &a
->address
.in
);
136 r
= sd_rtnl_message_read_in6_addr(m
, IFA_LOCAL
, &a
->address
.in6
);
138 r
= sd_rtnl_message_read_in6_addr(m
, IFA_ADDRESS
, &a
->address
.in6
);
154 qsort(list
, n_list
, sizeof(struct local_address
), address_compare
);