80
74

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アドレスが指定した範囲内にあるかどうか判別する

Posted at

アクセスしてきたIPアドレスが、サブネットマスクを含んだ指定のIPアドレスに該当するものかどうかを判断します。

$accept = '203.0.113.0/24';
$remote_ip = $_SERVER['REMOTE_ADDR'];

list($accept_ip, $mask) = explode('/', $accept);
$accept_long = ip2long($accept_ip) >> (32 - $mask);
$remote_long = ip2long($remote_ip) >> (32 - $mask);
if ($accept_long == $remote_long) {
    echo 'acceptable';
} else {
    echo 'not acceptable';
}

ip2long()で変換したものをビットシフトし、サブネットマスク部分同士(上の例だと上位24ビット)が同じかどうかを比較しています。

PHPマニュアル - ip2long
PHPマニュアル - ビット演算子

80
74
0

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
80
74

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?