dongyaofu0599 2010-11-18 10:30
浏览 269

PHP中的任何STUN / TURN / ICE客户端库?

I am trying to establish P2P between two PHP daemon deployed on machines in different network (both behind NAT). I searched around for NAT traversal using PHP on Google and seems like their is no existing solution for this in PHP.

Does anyone know about a solution/library to work this around with PHP?

  • 写回答

1条回答 默认 最新

  • doujun1495 2019-04-10 21:54
    关注

    If anybody else is looking for an answer, here is a simple class that does the job:

    <?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"
                ];
            }
    
        }
    
    }
    

    It's used like this:

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

报告相同问题?

悬赏问题

  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。