See if a server is listening on a port in PHP?

只愿长相守 提交于 2019-12-12 00:03:40

问题


Before answering, please note that I am completely new to PHP. I have heard it is powerful.

What I'm trying to do is have a page on my (Apache 2) web server that when a user clicks a button on the page, the server will check if a port is running on it's own IP with a preset port for each button, I want multiple buttons with the same IP but different ports to be pinged.

Example:

  • Button 1 (Terraria Server) is clicked, server pings 127.0.0.1:7777 and tells the user if it gets a response or not.

  • Button 2 (Minecraft Server) is clicked, server pings 127.0.0.1:25565 and tells the user etc etc.

I already have PHP installed and working, all I need is some code :)


回答1:


Attempt a connection on the port and return the result:

 <?php
     function Connect($port) {
        $serverConn = @stream_socket_client("tcp://127.0.0.1:{$port}", $errno, $errstr);
        if ($errstr != '') {
            return false;
        }
       fclose($serverConn);
       return true;
      } 


    if(isset($_POST['portTest'])){
       switch ($_POST['portTest']){
           case 'minecraft': $port= '25565';
        break;
           case 'Terraria': $port= '7777';
        break;  
           default: exit;
       }
     if (Connect($port)){
         echo "Server is running!";
       }else{
         echo "Server is down";
       }
    }
    ?> 

    <form method="POST">
    <input type="submit" name="portTest" value="minecraft">
    <input type="submit" name="portTest" value="Terraria">
    </form>


来源:https://stackoverflow.com/questions/23300255/see-if-a-server-is-listening-on-a-port-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!