How to convert ipaddress / mask to CIDR using C ++?

I have an ipaddress / mask list that needs to be converted to CIDR notation.

eg. 12.174.36.240/24 needs to be converted to 12.174.36.0/24 or something like http://www.subnet-calculator.com/cidr.php does

How can this be achieved?

PS: the mask value is not always 24.

+4
source share
2 answers

To lead you in the right direction, consider what an IPv4 address is (a 32-bit integer). Now consider what a mask is (a bit field used in bitwise operations).

127.0.0.1 . 0x7f000001. 24- 0xffffff00 (24 1, 8 0, 32 ). 0x7f000001 & 0xffffff00 = 0x7f000000 - CIDR.

, , , IPv4 ( ) , , , , .

+2

, IPV4- 32- , 8 .

, "a.b.c.d", ,

(a<<24) + (b<<16) + (c<<8) + d 

< . , a<<b a*2^b

CIDR , ( 32) . . 10.10.10.1/28 28- 32-28 = 4- . , ip (= 0x0A0A0A01) & 0xFFFFFFFF < 4 (= 0xFFFFFFF0), 0x0A0A0A00. ip :

sprintf("%d.%d.%d.%d", (n>>24)&0xff, (n>>16)&0xff, (n>>8)&0xff, n&0xff) 

10.10.10.0. , 0xFFFFFFF0 ip , 255.255.255.248, , 28.

IPv6 , , 128 8 16- , , 0 (::)..

.

fe80::52e5:49ff:ffc9:1889/64 == 

;;convert the mask 
0xffffffffffffffffffffffffffffffff << (128-64) =
0xffffffffffffffff0000000000000000

;;convert the ip:
fe80::52e5:49ff:ffc9:1889 ==
fe80:0000:0000:0000:52e5:49ff:ffc9:1889 ==
0xfe8000000000000052e549ffffc91889 

  0xfe8000000000000052e549ffffc91889
& 0xffffffffffffffff0000000000000000
= 0xfe800000000000000000000000000000

;;convert first address in range back to string:
fe80:0000:0000:0000:0000:0000:0000:0000 = 
fe80::

, , , .

+2

All Articles