PHP套接字连接- Telnet拒绝连接


PHP Socket Connection - Telnet refused to connect

我编写了一个小类来管理PHP中的套接字连接:

    #/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 localhost

PORT     STATE SERVICE
5000/tcp open  upnp

但是,如果我尝试使用telnet连接:

telnet SERVER_IP 5000 I get:
Trying SERVER_IP...
telnet: connect to address SERVER_IP: Connection refused
telnet: Unable to connect to remote host

我也尝试改变iptables以接受端口,但它没有工作,但可能我只是做错了。

还有什么我可以试试的主意吗?

  • xcode

你必须改变:

define('IP', '127.0.0.1');

:

define('IP', '0.0.0.0');

通过使用127.0.0.1,您将只能从服务器本身进行连接,因为它绑定到127.0.0.1,正如netstat所示。