Foad Tahmasebi
Foad Tahmasebi

Reputation: 1352

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?

Upvotes: 0

Views: 5961

Answers (2)

Jay Blanchard
Jay Blanchard

Reputation: 34426

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.

Upvotes: 2

Faiz Rasool
Faiz Rasool

Reputation: 1379

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

Upvotes: 0

Related Questions