gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 21:45:39 25 4
gpt4 key购买 nike

我正在尝试在部署在不同网络(均在 NAT 之后)的机器上的两个 PHP 守护程序之间建立 P2P。我在 Google 上搜索了使用 PHP 的 NAT 遍历,似乎他们在 PHP 中没有针对此问题的现有解决方案。

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

最佳答案

如果其他人正在寻找答案,这里有一个简单的类可以完成这项工作:

<?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

关于php - PHP 中的任何 STUN/TURN/ICE 客户端库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4213805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com