Ozair Patel
Ozair Patel

Reputation: 1926

PHP Socket Not Listening

include 'config.php';
set_time_limit(0);
//sending message
$msgOkay = "okay";
$msg1 = "1";
$msg2 = "2";
$msg3 = "3";
$msg4 = "4";
$msg5 = "5";
$msg6 = "6";

echo "Starting Listening Master. \n";

$sock = socket_create(AF_INET, SOCK_STREAM, 0);
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 0))){
    $errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);

    die("Failed to create socket: [$errorcode] $errormsg \n");
}
echo "Socket created! \n";
socket_bind($sock, 0, 899);
echo "Socket Bound \n";
while (true) {

socket_listen($sock, 100);
echo "Listening for connections \n";
$client = socket_accept($sock);
echo "Connection Established. \n";
if(socket_getpeername($client , $address, $port)){
    echo "Client $address : $port has successfully established connection with socket master. \n";
}

$input = socket_read($client);
$request = explode("\n", $input);
if($request[0] == "dovote"){
    $key = $request[1];
    $id = $request[2];
    $player = $request[3];
    $ip = $request[4];



}

elseif($request[0] == "test"){
    $key = $request[1];
    $id = $request[2];
    $player = $request[3];
    $ip = $request[4];  

    $QueryTest = ("SELECT * FROM socketmanager WHERE privatekey = '".$key."' AND id = '".$id."'");
    $resultTest = mysql_query($QueryTest);
    if(mysql_num_rows($resultAuth) == "1"){
        socket_send($sock, $msg1, strlen($msg1), 0);
    }
    else{
        socket_send($sock, $msg3, strlen($msg3), 0);
    }

}

else{
    if(!socket_send($sock, $msg3, strnlen($msg3), 0)){
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        die("Could not send data: [$errorcode] $errormsg \n");
    }
}



}

I've uploaded this to my web server, which is a VPS, where I control everything (port 899 is open). Whereas when on my Mac I run:

telnet
open ip 80

It opens it and closes it. On the webserver, I run the script and I see nothing except "Listening for connections"

Upvotes: 2

Views: 271

Answers (1)

Sunry
Sunry

Reputation: 612

I think it's about permission problems:

Non-root user can't bind port below 1024.
SELinux limitation or firewall problems.

You should check socket_bind() and socket_listen() return TRUE or FALSE, then debug deep into it.

Upvotes: 1

Related Questions