+
+ /**
+ * Converts ip address to hexadecimal string
+ *
+ * Function is used to convert ipv4 and ipv6 addresses to hex strings.
+ * It removes all delimiter symbols from ip addresses, converts decimal
+ * ipv4 numbers to hex and pads strings in order to present full length
+ * address. ipv4 addresses are represented as 8 byte strings, ipv6 addresses
+ * are represented as 32 byte string.
+ *
+ * If function fails to detect address format, it returns unprocessed string.
+ * @param string $string ip address string
+ * @return string processed ip address string
+ * @since 1.5.1 and 1.4.5
+ */
+ function ip2hex($string) {
+ if (preg_match("/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/",$string,$match)) {
+ // ipv4 address
+ $ret = str_pad(dechex($match[1]),2,'0',STR_PAD_LEFT)
+ . str_pad(dechex($match[2]),2,'0',STR_PAD_LEFT)
+ . str_pad(dechex($match[3]),2,'0',STR_PAD_LEFT)
+ . str_pad(dechex($match[4]),2,'0',STR_PAD_LEFT);
+ } elseif (preg_match("/^([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)\:([0-9a-h]+)$/i",$string,$match)) {
+ // full ipv6 address
+ $ret = str_pad($match[1],4,'0',STR_PAD_LEFT)
+ . str_pad($match[2],4,'0',STR_PAD_LEFT)
+ . str_pad($match[3],4,'0',STR_PAD_LEFT)
+ . str_pad($match[4],4,'0',STR_PAD_LEFT)
+ . str_pad($match[5],4,'0',STR_PAD_LEFT)
+ . str_pad($match[6],4,'0',STR_PAD_LEFT)
+ . str_pad($match[7],4,'0',STR_PAD_LEFT)
+ . str_pad($match[8],4,'0',STR_PAD_LEFT);
+ } elseif (preg_match("/^\:\:([0-9a-h\:]+)$/i",$string,$match)) {
+ // short ipv6 with all starting symbols nulled
+ $aAddr=explode(':',$match[1]);
+ $ret='';
+ foreach ($aAddr as $addr) {
+ $ret.=str_pad($addr,4,'0',STR_PAD_LEFT);
+ }
+ $ret=str_pad($ret,32,'0',STR_PAD_LEFT);
+ } elseif (preg_match("/^([0-9a-h\:]+)::([0-9a-h\:]+)$/i",$string,$match)) {
+ // short ipv6 with middle part nulled
+ $aStart=explode(':',$match[1]);
+ $sStart='';
+ foreach($aStart as $addr) {
+ $sStart.=str_pad($addr,4,'0',STR_PAD_LEFT);
+ }
+ $aEnd = explode(':',$match[2]);
+ $sEnd='';
+ foreach($aEnd as $addr) {
+ $sEnd.=str_pad($addr,4,'0',STR_PAD_LEFT);
+ }
+ $ret = $sStart
+ . str_pad('',(32 - strlen($sStart . $sEnd)),'0',STR_PAD_LEFT)
+ . $sEnd;
+ } else {
+ // unknown addressing
+ $ret = $string;
+ }
+ return $ret;
+ }