我正在尝试使用PHP生成随机公共IP地址。我希望得到关于我所做的功能的反馈,如下所示。您认为有哪些方面可以改进它的编码方式?可以用更少的代码行完成吗?是否有我未提供的保留号码?我应该使用mt_rand()而不是rand()吗?所有反馈都赞赏。感谢。
function generateIP() {
$q1 = rand(3,253);
//stop the first quadrant being one from a resrved range
while ($q1 == '10'|| $q1 == '100'|| $q1 == '127' || $q1 == '169' || $q1 == '172' || $q1 == '192' || $q1 == '198' || $q1 == '203' || $q1 == '224' || $q1 == '240') {
$q1 = rand(3,253);
}
$q2 = rand(0,255);
$q3 = rand(0,255);
$q4 = rand(0,255);
$ip = $q1.'.'.$q2.'.'.$q3.'.'.$q4;
return $ip;
}
答案 0 :(得分:1)
怎么样?
function generateIP() {
$q1 = 0;
do
{
$q1 = rand(1,255);
}
while($q1 != '0'|| $q1 != '10'|| $q1 != '100'|| $q1 != '127' || $q1 != '169' || $q1 != '172' || $q1 != '192' || $q1 != '198' || $q1 != '203' || $q1 != '224' || $q1 != '240'){
$q2 = rand(0,255);
$q3 = rand(0,255);
$q4 = rand(0,255);
$ip = $q1.'.'.$q2.'.'.$q3.'.'.$q4;
return $ip;
};
答案 1 :(得分:-1)
在RANGE中生成IP
public static function generateRandomIp($start, $end) {
if (strcmp($start, $end) > 0) {
return false;
}
$arrStart = explode('.',$start);
$arrEnd = explode('.', $end);
// First
$arrIp[0] = rand($arrStart[0], $arrEnd[0]);
// Second
if ($arrIp[0] == $arrStart[0] && $arrIp[0] == $arrEnd[0]) {
$arrIp[1] = rand($arrStart[1], $arrEnd[1]);
} elseif ($arrIp[0] == $arrStart[0]) {
$arrIp[1] = rand($arrStart[1], 255);
} elseif ($arrIp[0] == $arrEnd[0]) {
$arrIp[1] = rand(0, $arrEnd[1]);
} else {
$arrIp[1] = rand(0, 255);
}
// Third
if ($arrIp[1] == $arrStart[1] && $arrIp[1] == $arrEnd[1]) {
$arrIp[2] = rand($arrStart[2], $arrEnd[2]);
} elseif ($arrIp[1] == $arrStart[1]) {
$arrIp[2] = rand($arrStart[2], 255);
} elseif ($arrIp[1] == $arrEnd[1]) {
$arrIp[2] = rand(0, $arrEnd[2]);
} else {
$arrIp[2] = rand(0, 255);
}
// Fourth
if ($arrIp[2] == $arrStart[2] && $arrIp[02] == $arrEnd[2]) {
$arrIp[3] = rand($arrStart[3], $arrEnd[3]);
} elseif ($arrIp[2] == $arrStart[2]) {
$arrIp[3] = rand($arrStart[3], 255);
} elseif ($arrIp[2] == $arrEnd[2]) {
$arrIp[3] = rand(0, $arrEnd[3]);
} else {
$arrIp[3] = rand(0, 255);
}
return implode(".", $arrIp);
}
答案 2 :(得分:-1)
sprintf("%s.%s.%s.%s",
rand(0,255),
rand(0,255),
rand(0,255),
rand(0,255)
);