PHP高级工程师|全栈工程师|WX: Aben_Ring

php socket 循环ping ip,显示能ping通的IP地址

预览

index.php 代码

<?php
function ping2($host) {
    $port = 80;
    $buff = "123456789"; //测试字符串

    // ipv6
    //$socket = @socket_create(AF_INET6, SOCK_DGRAM, SOL_UDP);

    // ipv4
    $socket = @socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

    //发送超时1秒
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));
    //接收超时1秒
    socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array("sec" => 1, "usec" => 0));

    if (!$socket) return false;
    
    @socket_sendto($socket, $buff, strlen($buff), 0, $host, $port);
    $read = array($socket);
    $write = NULL;
    $except = NULL;
    if (@socket_select($read, $write, $except, 1) > 0) {
        return true;
    } else {
        return false;
    }
    @socket_close($socket);
}


function ping($host) {
    $icmp_socket = socket_create(AF_INET, SOCK_RAW, 1);
    socket_set_block($icmp_socket);
    socket_set_option($icmp_socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));

    /* connect to socket */
    socket_connect($icmp_socket, $host, null);

    /* 创建一个发送包*/
    $request = "\x08\x00\x19\x2f\x00\x00\x00\x00\x70\x69\x6e\x67";

    socket_send($icmp_socket, $request, strlen($request), 0);

    if (@socket_read($icmp_socket, 255)) {
        return true;
    } else {
        return false;
    }
    socket_close($icmp_socket);
}

$ip = $_GET['ip'];
if ($ip) {
    $result = ping($ip);
    if ($result) {
        echo "success";
    }
} else {
    $base = $_GET['base'] ?: "192.168.1";
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Ping</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<!-- 
url访问方式:
http://localhost/ping.php
http://localhost/ping.php?base=192.168.137
-->
<script type="text/javascript">
    $(function () {
        var num = 1;
        var ticket = setInterval(function () {
            if (num > 255) {
                clearInterval(ticket);
                return false;
            }
            var ip = '<?=$base?>.' + num;
            $.get("/ping.php?ip=" + ip, function (data) {
                console.log(data)
                if (data === 'success') {
                    $("body").append(ip + "<br/>")
                }
            })
            num++;
        }, 200)
    })
</script>
</body>
</html>
<?php } ?>
posted @ 2021-05-13 11:09  懒牛拉车  阅读(281)  评论(0编辑  收藏  举报