如何在php中检查UDP端口是否侦听?

时间:2015-06-15 12:42:40

标签: php sockets udp

我在侦听UDP端口的服务器上有一项服务。我怎样才能检查我的服务是否仍然通过php监听此端口?

我认为UDP是单向的,不会在创建连接时返回任何内容(实际上没有连接:))我应该写入套接字。

但是,无论我是否成功写入套接字,我都会收到'true'!

我的代码:

if(!$fp = fsockopen('udp://192.168.13.26', 9996, $errno, $errstr, 1)) {
     echo 'false';
} else {
    if(fwrite($fp, 'test')){
        echo 'true';
    }else{
        echo 'false';
    }
}
你有什么建议吗?

2 个答案:

答案 0 :(得分:2)

You should really switch to the Sockets library for creating sockets:

$ip = '192.168.13.26';
// create a UDP socket
if(!($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

// bind the source address
if( !socket_bind($sock, $ip, 9996) ) {
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Could not bind socket : [$errorcode] $errormsg \n");
}

The only way to see if a socket is still open is to post a message to it, but given the nature of UDP there are no guarantees.

答案 1 :(得分:0)

正如PHP官方文档所述

  

fsockopen()返回一个文件指针,可以与。一起使用   其他文件函数(如fgets(),fgetss(),fwrite(),fclose(),   和feof())。如果通话失败,则将返回FALSE

所以你可以这样做来检查错误

$fp = fsockopen("udp://192.168.13.26", 9996, $errno, $errstr);
if (!$fp) {
    echo "ERROR: $errno - $errstr<br />\n";
} else {
    fwrite($fp, "\n");
    echo fread($fp, 26);
    fclose($fp);
}
相关问题