简体   繁体   中英

How to check UDP port listen or not in php?

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?

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM