如何使用PHP套接字进行NAT

时间:2014-04-06 20:41:59

标签: php sockets udp nat stun

我试图在php中创建一个点对点应用程序,以同样的方式工作。它适用于内部地址,但是当我尝试将数据发送到外部地址时,消息永远不会到达。显然我错过了一些地址转换,但我对如何使用PHP套接字感到茫然。有可能吗?

这是我目前收到消息的代码,我先运行该消息等待一些消息:

<?php
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or die("Could not create socket: " . socket_strerror(socket_last_error($socket)));
socket_bind($socket, "0.0.0.0", 100) or die("Could not bind socket: " . socket_strerror(socket_last_error($socket)));

$ret = "";
$from_ip = "";
$from_port = 0;


echo "waiting...\n";
socket_recvfrom($socket, $ret, 6, 0, $from_ip, $from_port);

var_dump($ret, $from_ip, $from_port);

socket_close($socket);

然后在等待时,我运行此代码发送消息:

<?php
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or die("Could not create socket: " . socket_strerror(socket_last_error($socket)));


$to_ip = "externalip"; //works with internal "127.0.0.1";
$to_port = 100;
$message = "hello!";

socket_sendto($socket, $message, strlen($message), 0, $to_ip, $to_port);
echo "sent\n";

socket_close($socket);

但它发送和退出,但第一个脚本仍在等待...... 已经有一段时间了,有人可以帮帮我吗?

- 编辑 -

好的,我已经实现了一个昏迷服务器并为它设置了端口转发:

<?php

echo "-- STUN SERVER --\n";

$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or die("Could not create socket: " . socket_strerror(socket_last_error($socket)));
socket_bind($socket, "0.0.0.0", 5104) or die("Could not bind socket: " . socket_strerror(socket_last_error($socket)));


do {
    $ret = "";
    $from = "";
    $port = 0;

    echo "waiting...\n";
    socket_recvfrom($socket, $ret, 6, 0, $from, $port);

    echo "received: $ret\n";

    $message = $from.":".$port;
    socket_sendto($socket, $message, strlen($message), 0, $from, $port);
    echo "sent: $message\n\n";
}
while (true);

并更改了我的第一个脚本以从stun服务器获取其ip / port:

<?php
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or die("Could not create socket: " . socket_strerror(socket_last_error($socket)));
socket_bind($socket, "0.0.0.0", 100) or die("Could not bind socket: " . socket_strerror(socket_last_error($socket)));

$ret = "";
$from = "";
$port = 0;


echo "sending info to stun server...\n";
$to_ip = "stunip";
$to_port = 5104;
$message = "get_ip";
socket_sendto($socket, $message, strlen($message), 0, $to_ip, $to_port);

echo "waiting for stun...\n";
$stuninfo = "";
socket_recvfrom($socket, $stuninfo, 25, 0, $from, $port);

var_dump($stuninfo); // i use this info in my second script


echo "waiting...\n";
socket_recvfrom($socket, $ret, 6, 0, $from, $port);

var_dump($ret, $from, $port);

socket_close($socket);

它从stun服务器获取信息ok并等待另一个连接,但是当我在我的第二个脚本中使用该信息时,第一个脚本仍然没有收到任何消息..还有另一个步骤我&#39我失踪了?

0 个答案:

没有答案