简体   繁体   English

将 ip 短符号转换为 CIDR 符号

[英]convert ip short notation into CIDR notation

suppose I have a list like this below (in array $ips) which includes simple ip addresses and ip in short ip notation style.假设我有一个像下面这样的列表(在数组 $ips 中),其中包括简单的 ip 地址和 ip 简而言之 ip 表示法样式。

125.45.
201.35.1.
35.89.18.27
101.135.2
222.122
78.56.21.146

how to convert them to ip Hyphenated range using php?如何使用 php 将它们转换为 ip 连字符范围?

ie the result should be即结果应该是

125.45.0.0-125.45.255.255
201.35.1.0-201.35.1.255
35.89.18.27
101.135.2.0-101.135.2.255
222.122.0.0-222.122.255.255 
78.56.21.146

Note, that I did this as a fun experiment.请注意,我这样做是为了做一个有趣的实验。 Your question was a little vague, and you showed no attempt to actually to this yourself.你的问题有点含糊,你自己也没有表现出真正的尝试。 That being said, this function should accomplish what you are wanting.话虽如此,这个 function 应该可以完成您想要的。 Let me explain what it does:让我解释一下它的作用:

First thing, checks if last character in the ip is a dot and removes it.首先,检查 ip 中的最后一个字符是否为点并将其删除。

Second, count the number of ranges your IP has.其次,计算您的 IP 具有的范围数。

Third use a switch/case statement (cleaner than if elseif IMHO) to determine what to do with the string, based on IP range.第三,根据 IP 范围,使用switch/case语句(比if elseif恕我直言更简洁)来确定如何处理字符串。

Lastly define the starting range and the ending range and concatenate them.最后定义开始范围和结束范围并将它们连接起来。

Finally return result.最后返回结果。

<?php

$ips = array();


$ips[0] = '125.45.';
$ips[1] = '201.35.1.';
$ips[2] = '101.135.2';
$ips[3] = '222.122';
$ips[4] = '78.56.21.146';


foreach($ips as $ip){

echo "\n\nNEW IP RANGE: " . convert_ip($ip) . "\n\n";

}

function convert_ip($ip){

$ip = rtrim($ip, '.');

$ip_count = count( explode('.', $ip) );

switch ($ip_count) {

    case 1:

        $starting_ip = $ip . '.0.0.0';

        $ending_ip = $ip . '.255.255.255';

        $return_ip = "$starting_ip-$ending_ip";

        break;
    case 2:

        $starting_ip = $ip . '.0.0';

        $ending_ip = $ip . '.255.255';

        $return_ip = "$starting_ip-$ending_ip";

        break;
    case 3:

        $starting_ip = $ip . '.0';

        $ending_ip = $ip . '.255';

        $return_ip = "$starting_ip-$ending_ip";

        break;
    case 4:

        $return_ip = $ip;

        break;

    default:
        $return_ip = 'Unknown';
}

return $return_ip;

}

?>

NEW IP RANGE: 125.45.0.0-125.45.255.255新 IP 范围:125.45.0.0-125.45.255.255

NEW IP RANGE: 201.35.1.0-201.35.1.255新 IP 范围:201.35.1.0-201.35.1.255

NEW IP RANGE: 101.135.2.0-101.135.2.255新 IP 范围:101.135.2.0-101.135.2.255

NEW IP RANGE: 222.122.0.0-222.122.255.255新 IP 范围:222.122.0.0-222.122.255.255

NEW IP RANGE: 78.56.21.146新 IP 范围:78.56.21.146

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM