1/* 2 * (C) 2006-2008 by Pablo Neira Ayuso <pablo@netfilter.org> 3 * 4 * This program is free software; you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation; either version 2 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program; if not, write to the Free Software 16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 17 */ 18 19#include <stdint.h> 20#include <string.h> 21#include <netinet/in.h> 22#include "cidr.h" 23 24/* returns the netmask in host byte order */ 25uint32_t ipv4_cidr2mask_host(uint8_t cidr) 26{ 27 return 0xFFFFFFFF << (32 - cidr); 28} 29 30/* returns the netmask in network byte order */ 31uint32_t ipv4_cidr2mask_net(uint8_t cidr) 32{ 33 return htonl(ipv4_cidr2mask_host(cidr)); 34} 35 36void ipv6_cidr2mask_host(uint8_t cidr, uint32_t *res) 37{ 38 int i, j; 39 40 memset(res, 0, sizeof(uint32_t)*4); 41 for (i = 0; i < 4 && cidr > 32; i++) { 42 res[i] = 0xFFFFFFFF; 43 cidr -= 32; 44 } 45 res[i] = 0xFFFFFFFF << (32 - cidr); 46 for (j = i+1; j < 4; j++) { 47 res[j] = 0; 48 } 49} 50 51void ipv6_cidr2mask_net(uint8_t cidr, uint32_t *res) 52{ 53 int i; 54 55 ipv6_cidr2mask_host(cidr, res); 56 for (i=0; i<4; i++) 57 res[i] = htonl(res[i]); 58} 59 60/* I need this function because I initially defined an IPv6 address as 61 * uint32 u[4]. Using char u[16] instead would allow to remove this. */ 62void ipv6_addr2addr_host(uint32_t *addr, uint32_t *res) 63{ 64 int i; 65 66 memset(res, 0, sizeof(uint32_t)*4); 67 for (i = 0; i < 4; i++) { 68 res[i] = ntohl(addr[i]); 69 } 70} 71