Skip to content

Instantly share code, notes, and snippets.

@GaneshKandu
Last active September 26, 2016 11:44
Show Gist options
  • Save GaneshKandu/e61599909de3b081734dbc8504694352 to your computer and use it in GitHub Desktop.
Save GaneshKandu/e61599909de3b081734dbc8504694352 to your computer and use it in GitHub Desktop.
HEXT TO IP And IP TO HEX
<?php
/*
*
* @author Ganesh Kandu (mailto:kanduganesh@gmail.com)
*
*/
class HexIP{
function IP2Hex($ip) {
$hex = "";
$part = explode(".",$ip);
foreach($part as $value)
{
if($value > 255 && $value > -1){
throw new RuntimeException('The Provided IP is Not Valid');
die();
}
if(strlen($value) < 2){
$hex .= "0".dechex($value);
}else{
$hex .= dechex($value);
}
}
return strtoupper($hex);
}
function Hex2IP($hex) {
$ip = "";
$ippart = array();
if(strlen($hex) > 8){
throw new RuntimeException('The Provided Hex is Not Valid');
die();
}
$ippart[0] = substr($hex,0,2);
$ippart[1] = substr($hex,2,2);
$ippart[2] = substr($hex,4,2);
$ippart[3] = substr($hex,6,2);
foreach($ippart as $key => $value){
$ippart[$key] = hexdec($value);
}
$ip = implode(".",$ippart);
return $ip;
}
}
$a = new HexIP();
echo "<br/>HEXT TO IP<br/>";
echo $a->Hex2IP("C0A80119");
echo "<br/>IP TO HEX<br/>";
echo $a->IP2Hex("192.168.1.25");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment