0
我寫了一個小的類在PHP管理套接字連接:PHP Socket連接 - 遠程登錄拒絕連接
#/usr/bin/php
<?php
define('PORT', 5000);
define('IP', '127.0.0.1');
/**
* SocketManager
*/
class SocketManager {
private $sock = null;
public $errorcode = null;
public $errormsg = null;
public $client = null;
public function initSocket($onConnect) {
echo "Init Socket\n";
if (!($this->sock = socket_create(AF_INET, SOCK_STREAM, 0))) {
$this->errorcode = socket_last_error();
$thid->errormsg = socket_strerror($errorcode);
return;
}
echo "Created Socket\n";
if (!socket_bind($this->sock, IP , PORT)) {
$this->errorcode = socket_last_error();
$thid->errormsg = socket_strerror($errorcode);
return;
}
echo "Bind Socket\n";
if(!socket_listen($this->sock , 10)) {
$this->errorcode = socket_last_error();
$thid->errormsg = socket_strerror($errorcode);
return;
}
echo "Listening on " . PORT . "\n";
while (true) {
echo ".";
$this->client = socket_accept($this->sock);
if(socket_getpeername($client , $address , $port)) {
if (!is_null($onConnect)) {
call_user_func_array($onConnect,array($client,$address,$port));
}
}
}
}
function __construct($onConnect) {
$this->initSocket($onConnect);
}
}
function handleConnection($client,$address,$port) {
echo "User Connected: $address\n";
}
$socket = new SocketManager("handleConnection");
?>
開始,這將導致以下的輸出:
#/usr/bin/php
Init Socket
Created Socket
Bind Socket
Listening on 5000
.
用netstat打印出檢查如下:
netstat -nap | grep的LISTEN
tcp 0 0 127.0.0.1:5000 0.0.0.0:* LISTEN 32301/php
而且還NMAP告訴我5000被打開的端口:
的nmap -p 5000本地主機
PORT STATE SERVICE
5000/tcp open upnp
但是仍然,如果我嘗試使用telnet連接:
telnet SERVER_IP 5000我得到:
Trying SERVER_IP...
telnet: connect to address SERVER_IP: Connection refused
telnet: Unable to connect to remote host
我也嘗試改變iptables接受端口,但它沒有工作,但它可能是我做錯了。
其他想法我可以嘗試嗎?
- xCoder
我想你正試圖遠程登錄,而你綁定到127.0.0.1。只需將IP更改爲0.0.0.0,然後即可連接。 – VolenD
謝謝,這對我有用!如果你讓它成爲答案,我可以將其標記爲正確。 – xCoder