How to check UDP port listen or not in php?

2019-09-09 00:06发布

I have a service on a server that listen to a UDP port. how can I check my service still listen on this port or not by php?

I think UDP is one-way and don't return anything on create a connection (in fact there is no connection :)) and I should write to a socket.

but, whether I write successfully to a socket or not, I receive 'true'!

my code:

if(!$fp = fsockopen('udp://192.168.13.26', 9996, $errno, $errstr, 1)) {
     echo 'false';
} else {
    if(fwrite($fp, 'test')){
        echo 'true';
    }else{
        echo 'false';
    }
}

do you have any suggestion for this?

标签: php sockets udp
2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-09 00:52

As PHP official documentation said

fsockopen() returns a file pointer which may be used together with the other file functions (such as fgets(), fgetss(), fwrite(), fclose(), and feof()). If the call fails, it will return FALSE

So you can do this to check the error

$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);
}
查看更多
放荡不羁爱自由
3楼-- · 2019-09-09 01:09

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.

查看更多
登录 后发表回答