您正在寻找的是NAT traversal。没有中继服务器和端口转发的解决方案通常使用某种形式的UDP 打孔。一种标准化的机制是STUN(即交互式连接建立)。
注意:通过 UDP 实现 UDP 打孔和可靠的文件传输并非易事。最好的选择可能是使用 UPnP 或 NAT-PMP 自动设置端口转发。两者都有库,例如Mono.Nat ( sources ):
class NatTest
{
public Start ()
{
// Hook into the events so you know when a router
// has been detected or has gone offline
NatUtility.DeviceFound += DeviceFound;
NatUtility.DeviceLost += DeviceLost;
// Start searching for upnp enabled routers
NatUtility.StartDiscovery ();
}
void DeviceFound(object sender, DeviceEventArgs args)
{
// This is the upnp enabled router
INatDevice device = args.Device;
// Create a mapping to forward external port 3000 to local port 1500
device.CreatePortMap(new Mapping(Protocol.Tcp, 1500, 3000));
// Retrieve the details for the port map for external port 3000
Mapping m = device.GetSpecificMapping(Protocol.Tcp, 3000);
// Get all the port mappings on the device and delete them
foreach (Mapping mp in device.GetAllMappings())
device.DeletePortMap(mp);
// Get the external IP address
IPAddress externalIP = device.GetExternalIP();
}
private void DeviceLost (object sender, DeviceEventArgs args)
{
INatDevice device = args.Device;
Console.WriteLine ("Device Lost");
Console.WriteLine ("Type: {0}", device.GetType().Name);
}
}