Skip to content

Instantly share code, notes, and snippets.

@MrRaindrop
Created October 13, 2014 14:48
Show Gist options
  • Save MrRaindrop/06e8a0da8f1e22b254e4 to your computer and use it in GitHub Desktop.
Save MrRaindrop/06e8a0da8f1e22b254e4 to your computer and use it in GitHub Desktop.
php: calculate subnet addresses
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>testCalcSubnet</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
IP Address:
<br/><input type="text" name="ip[]" size="3" maxlength="3" />
<input type="text" name="ip[]" size="3" maxlength="3" />
<input type="text" name="ip[]" size="3" maxlength="3" />
<input type="text" name="ip[]" size="3" maxlength="3" />
<br/>
<br/>Subnet Mask:
<br/><input type="text" name="sm[]" size="3" maxlength="3" />
<input type="text" name="sm[]" size="3" maxlength="3" />
<input type="text" name="sm[]" size="3" maxlength="3" />
<input type="text" name="sm[]" size="3" maxlength="3" />
<br/>
<br/><input type="submit" name="submit" value="submit" />
</form>
<?php
if (isset($_POST['submit'])) {
$ip = implode('.', $_POST['ip']);
$ip = ip2long($ip);
$netmask = implode('.', $_POST['sm']);
$netmask = ip2long($netmask);
// 计算网络地址
$na = $ip & $netmask;
// 计算广播地址
$ba = $ip | (~$netmask);
// display
echo "<br/>Address Information:";
echo "<ul>";
echo "<li>Ip Address: " . long2ip($ip) . "</li>";
echo "<li>Subnet Mask: " . long2ip($netmask) . "</li>";
echo "<li>Network Address: " . long2ip($na) . "</li>";
echo "<li>Broadcast Address: " . long2ip($ba) . "</li>";
echo "<li>Total Available Hosts: " . ($ba - $na - 1) . "</li>";
echo "<li>Host Range: " . long2ip($na + 1) . " - " . long2ip($ba - 1) . "</li>";
} else {
echo "<br/>submit is not set!";
}
?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment