xref: /freebsd/sbin/ipf/libipf/ntomask.c (revision efeb8bffe34422937c7f8df836afb5b817366d16)
141edb306SCy Schubert /*	$FreeBSD$	*/
241edb306SCy Schubert 
341edb306SCy Schubert /*
441edb306SCy Schubert  * Copyright (C) 2012 by Darren Reed.
541edb306SCy Schubert  *
641edb306SCy Schubert  * See the IPFILTER.LICENCE file for details on licencing.
741edb306SCy Schubert  *
841edb306SCy Schubert  * $Id$
941edb306SCy Schubert  */
1041edb306SCy Schubert 
1141edb306SCy Schubert #include "ipf.h"
1241edb306SCy Schubert 
13*efeb8bffSCy Schubert int
14*efeb8bffSCy Schubert ntomask(int family, int nbits, u_32_t *ap)
1541edb306SCy Schubert {
1641edb306SCy Schubert 	u_32_t mask;
1741edb306SCy Schubert 
1841edb306SCy Schubert 	if (nbits < 0)
1941edb306SCy Schubert 		return -1;
2041edb306SCy Schubert 
2141edb306SCy Schubert 	switch (family)
2241edb306SCy Schubert 	{
2341edb306SCy Schubert 	case AF_INET :
2441edb306SCy Schubert 		if (nbits > 32 || use_inet6 == 1)
2541edb306SCy Schubert 			return -1;
2641edb306SCy Schubert 		if (nbits == 0) {
2741edb306SCy Schubert 			mask = 0;
2841edb306SCy Schubert 		} else {
2941edb306SCy Schubert 			mask = 0xffffffff;
3041edb306SCy Schubert 			mask <<= (32 - nbits);
3141edb306SCy Schubert 		}
3241edb306SCy Schubert 		*ap = htonl(mask);
3341edb306SCy Schubert 		break;
3441edb306SCy Schubert 
3541edb306SCy Schubert 	case 0 :
3641edb306SCy Schubert 	case AF_INET6 :
3741edb306SCy Schubert 		if ((nbits > 128) || (use_inet6 == -1))
3841edb306SCy Schubert 			return -1;
3941edb306SCy Schubert 		fill6bits(nbits, ap);
4041edb306SCy Schubert 		break;
4141edb306SCy Schubert 
4241edb306SCy Schubert 	default :
4341edb306SCy Schubert 		return -1;
4441edb306SCy Schubert 	}
4541edb306SCy Schubert 	return 0;
4641edb306SCy Schubert }
47