Saturday, 15 August 2015

php - Calculate and Convert IPv6 Address based on CIDR Prefix -


I have an IPv6 address with a CIDR prefix. Ex: 2001: 0: 3238: DFE1: 0063 :: efef / 32

I would like to write a function such that the IPv6 address matches the number of bits CIDR The prefix is ​​provided, this means if a prefix of 32 is provided, then 32 bits in the IP address should start from left and the remaining should be zero. In the above example, the desired output should be:

  2001: 0000: 0000: 0000: 0000: 0000: 0000: 0000/32  

I 2001 :: / 32

The CIDR prefix can range from 0-128.

It is based on this post so far what is mine, but I'm not sure it is giving the desired output. Can anyone see it and help? Am I thinking about the representation of CIDR directly?

  public function getCIDR metadata ($ ipAddress) {// address and prefix length divided into list ($ firstaddrstr, $ prefixlen) = explosion ('/', $ IPADDRESS); // Parse the address in a binary string $ firstaddrbin = inet_pton ($ firstaddrstr); // To convert binary string into hexadecimal characters with #expack (), the string is used with bin2hex () # unpack () for packing with perpendiculars ($) below $ firstaddrhex = reset (unpack (' H * ', $ firstaddrbin)); // Overwrite the first address string to ensure that the notation is optimal $ firstaddrstr = inet_ntop ($ firstaddrbin); $ CidrMatchedString = $ firstaddrstr '/'. $ Prefixlen; Countercurrent $ cidrMatchedString; }  

here:

  function getCIDRMatchedIP ($ IP) {if (strokes ($ IP, "::")! == incorrect) {$ parts = explosion (":", $ IP); $ Cnt = 0; // The number of numbers in that number ($ i = 0; $ i & lt; count ($ parts); $ i ++) {if (numeric_emeric ("0x". $ Parts [$ i]) $ Cnt ++; } // How many 0000 blocks is required $ required = 8 - $ cnt; $ Ip = str_replace ("::", str_repeat (": 0000", $ required), $ ip); } List ($ ip, $ prefix_len) = explosion ('/', $ ip); $ Parts = explosion (":", $ ip); // This start bit mask is $ bstring = str_repeat ("1", $ prefix_len) Str_repeat ("0", 128 - $ prefix_len); $ Mins = str_split ($ bstring, 16); $ Start = array (); For ($ i = 0; $ i & lt; 8; $ i ++) {$ min = base_convert ($ min [$ i], 2, 16); $ Start [] = sprintf ("% 04s", dickhex (hexdack ($ parts [$ i]) and hexack ($ min)); } $ Start = implode (':', $ start); Return $ start '/' $ prefix_len; }  

and you call the function getCIDRMatchedIP :

  echo getCIDRMatchedIP ('2001: 0: 3238: DFE1: 0063 :: FEFB / 32 ');  

No comments:

Post a Comment