2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

IPアドレスかどうかをチェックするPHPスクリプト

Last updated at Posted at 2014-12-19

概要

配列内の文字列がIPアドレスであればTrue、そうでなければFalseechoする

コード

ipcheck.php
<?php

$str = array("1.2.3...4", "1.2.3.4.", "hoge.2.3.4", "1.2.256.4", "1.2.3.4");


// IPをechoしてチェック結果を返す(メイン処理)
foreach ($str as $x) {
    echo "$x ";
    IPAddressCheck($x);
}


// IPアドレスかチェックして True or False を返す関数
// 3つの関数を使って判定
function IPAddressCheck($ipaddress) {
    if (DotCount($ipaddress) == "NG" || Bothendsoftheoctet($ipaddress) == "NG" || NumericalValueoftheOctet($ipaddress) == "NG") {
        SayAnswer("False");
    } else {
        SayAnswer("True");
    }
}


// 解をechoさせる
function SayAnswer ($answer) {
    echo "$answer" . PHP_EOL;
}


// ドットが3つか判定
function DotCount($ipaddress) {
    $dotcount = substr_count($ipaddress, '.');
    if ($dotcount !== 3) {
        return "NG";
    }
}

// 両端が数字かどうか判定
function BothEndsoftheOctet($ipaddress) {
    $octet = explode('.', $ipaddress);
    $octetcheck = $octet[0] . end($octet);
    if (ctype_digit($octetcheck) == FALSE) {
        return "NG";
    }
}

// 各オクテットが 0~255 でありまた数値か判定
function NumericalValueoftheOctet($ipaddress) {
    $octet = explode('.', $ipaddress);
    foreach ($octet as $y) {
        if (($y < 0) || ($y > 255) || (ctype_digit($y) == FALSE)) {
            return "NG";
            break;
        }
    }
}

?>

使用例

上記のコードをそのまま実行

$ php ipcheck.php
1.2.3...4 False
1.2.3.4. False
hoge.2.3.4 False
1.2.256.4 False
1.2.3.4 True

所感など

  • IPAddressCheckでのif文はもっとすっきりならないかなぁ
  • そもそもIPをチェックする関数がPHPには存在するらしいので、それも使用して書いてみたい
  • BothEndsoftheOctetは要らないかもしれない
  • 第1オクテットが0の場合は弾きたいなー
  • PrivateIPとGlobalIPのチェックもしたい
2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?