2 This file is part of catta.
4 catta is free software; you can redistribute it and/or modify it
5 under the terms of the GNU Lesser General Public License as
6 published by the Free Software Foundation; either version 2.1 of the
7 License, or (at your option) any later version.
9 catta is distributed in the hope that it will be useful, but WITHOUT
10 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
12 Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with catta; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
24 #include <sys/types.h>
25 #include <netinet/in.h>
26 #include <sys/socket.h>
27 #include <arpa/inet.h>
31 #include "addr-util.h"
33 CattaAddress *catta_address_from_sockaddr(const struct sockaddr* sa, CattaAddress *ret_addr) {
37 assert(sa->sa_family == AF_INET || sa->sa_family == AF_INET6);
39 ret_addr->proto = catta_af_to_proto(sa->sa_family);
41 if (sa->sa_family == AF_INET)
42 memcpy(&ret_addr->data.ipv4, &((const struct sockaddr_in*) sa)->sin_addr, sizeof(ret_addr->data.ipv4));
44 memcpy(&ret_addr->data.ipv6, &((const struct sockaddr_in6*) sa)->sin6_addr, sizeof(ret_addr->data.ipv6));
49 uint16_t catta_port_from_sockaddr(const struct sockaddr* sa) {
52 assert(sa->sa_family == AF_INET || sa->sa_family == AF_INET6);
54 if (sa->sa_family == AF_INET)
55 return ntohs(((const struct sockaddr_in*) sa)->sin_port);
57 return ntohs(((const struct sockaddr_in6*) sa)->sin6_port);
60 int catta_address_is_ipv4_in_ipv6(const CattaAddress *a) {
62 static const uint8_t ipv4_in_ipv6[] = {
63 0x00, 0x00, 0x00, 0x00,
64 0x00, 0x00, 0x00, 0x00,
65 0xFF, 0xFF, 0xFF, 0xFF
70 if (a->proto != CATTA_PROTO_INET6)
73 return memcmp(a->data.ipv6.address, ipv4_in_ipv6, sizeof(ipv4_in_ipv6)) == 0;
76 #define IPV4LL_NETWORK 0xA9FE0000L
77 #define IPV4LL_NETMASK 0xFFFF0000L
78 #define IPV6LL_NETWORK 0xFE80
79 #define IPV6LL_NETMASK 0xFFC0
81 int catta_address_is_link_local(const CattaAddress *a) {
84 if (a->proto == CATTA_PROTO_INET) {
85 uint32_t n = ntohl(a->data.ipv4.address);
86 return (n & IPV4LL_NETMASK) == IPV4LL_NETWORK;
88 else if (a->proto == CATTA_PROTO_INET6) {
89 unsigned n = (a->data.ipv6.address[0] << 8) | (a->data.ipv6.address[1] << 0);
90 return (n & IPV6LL_NETMASK) == IPV6LL_NETWORK;