代码之家  ›  专栏  ›  技术社区  ›  Abhinav Singh

PHP中有STUN/TURN/ICE客户端库吗?

  •  3
  • Abhinav Singh  · 技术社区  · 14 年前

    我试图在部署在不同网络(都在NAT后面)的机器上的两个PHP守护进程之间建立P2P。我在谷歌上搜索了使用PHP的NAT遍历,似乎他们在PHP中没有解决方案。

    有人知道用PHP解决这个问题的解决方案/库吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Nenad    6 年前

    如果其他人正在寻找答案,下面是一个简单的类:

    <?php
    
    class STUNClient
    {
        private $socket;
    
        public function __construct()
        {
            //stun.l.google.com
            $this->setServerAddr("66.102.1.127", 19302);
            $this->createSocket();
        }
    
        public function setServerAddr($host, $port = 3478)
        {
            $this->serverIP   = $host;
            $this->serverPort = $port;
        }
    
        public function createSocket()
        {
            $this->socket = socket_create(AF_INET, SOCK_DGRAM, getprotobyname("udp"));
            socket_set_nonblock($this->socket);
        }
    
        public function getPublicIp()
        {
            $msg = "\x00\x01\x00\x08\xc0\x0c\xee\x42\x7c\x20\x25\xa3\x3f\x0f\xa1\x7f\xfd\x7f\x00\x00\x00\x03\x00\x04\x00\x00\x00\x00";
    
            $numberOfBytesSent = socket_sendto($this->socket, $msg, strlen($msg), 0, $this->serverIP, $this->serverPort);
    
            $st = time();
            while (time() - $st < 1) {
    
                socket_recvfrom($this->socket, $data, 32, 0, $remoteIP, $remotePort);
    
                if (strlen($data) < 32) {
                    continue;
                }
                break;
            }
    
            try {
    
                $info = unpack("nport/C4s", substr($data, 26, 6));
                $ip   = sprintf("%u.%u.%u.%u", $info["s1"], $info["s2"], $info["s3"], $info["s4"]);
                $port = $info['port'];
                return [
                    'ip'   => $ip,
                    'port' => $port
                ];
            } catch (Exception $e) {
    
                return [
                    'ip'   => "0.0.0.0",
                    'port' => "0"
                ];
            }
    
        }
    
    }
    

    它是这样使用的:

    $sc  = new STUNClient;
    print_r( $sc->getPublicIp() ); //prnints out the public ip and port