Home > php教程 > php手册 > body text

php把IP地址转换成广播地址的例子

WBOY
Release: 2016-05-25 16:48:06
Original
873 people have browsed it

Broadcast Address(广播地址)是专门用于同时向网络中所有工作站进行发送的一个地址。在使用TCP/IP 协议的网络中,主机标识段host ID 为全1 的IP 地址为广播地址,广播的分组传送给host ID段所涉及的所有计算机

网络广播地址计算方法:

(1)IP地址与子网掩码进行"位与"运算,得到网络地址

(2)子网掩码"取反"运算,然后与网络地址进行"位或"运算,得到广播地址

<?php
//ip地址转换广播地址
private function ip2broadcast($ip, $mask) {
    $ipSplit = explode(&#39;.&#39;, $ip);
    $maskSplit = explode(&#39;.&#39;, $mask);
    $broadcast = null;
    for ($i = 0; $i < 4; $i++) {
        $ipBin = sprintf("%b", $ipSplit[$i]);
        while ((8 - strlen($ipBin)) > 0) $ipBin = "0" . $ipBin;
        $maskBin = sprintf("%b", $maskSplit[$i]);
        while ((8 - strlen($maskBin)) > 0) $maskBin = "0" . $maskBin;
        $broadcastBin = null;
        for ($j = 0; $j < 8; $j++) {
            $broadcastBin.= (!intval(substr($maskBin, $j, 1))) | (intval(substr($ipBin, $j, 1)) & intval(substr($maskBin, $j, 1)));
        }
        if ($i > 0) $broadcast.= ".";
        $broadcast.= bindec($broadcastBin);
    }
    return $broadcast;
}
Copy after login


教程链接:

随意转载~但请保留教程地址★

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!