|
| 1 | +using Open.Nat; |
| 2 | +using System; |
| 3 | +using System.Linq; |
| 4 | +using System.Net; |
| 5 | +using System.Text; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using UnityEngine; |
| 9 | + |
| 10 | +namespace MLAPI.Helper |
| 11 | +{ |
| 12 | + public class UPnPHelper |
| 13 | + { |
| 14 | + internal static void AttemptPortMap(int port, Action<bool, IPAddress> callback) |
| 15 | + { |
| 16 | + bool invoked = false; |
| 17 | + NatDiscoverer nat = new NatDiscoverer(); |
| 18 | + CancellationTokenSource cts = new CancellationTokenSource(); |
| 19 | + cts.CancelAfter(10000); |
| 20 | + |
| 21 | + NatDevice device = null; |
| 22 | + StringBuilder sb = new StringBuilder(); |
| 23 | + Task<NatDevice> natTask = nat.DiscoverDeviceAsync(PortMapper.Upnp, cts); |
| 24 | + Mapping tcpMapping = new Mapping(Protocol.Tcp, port, port, 0, Application.productName + " (TCP)"); |
| 25 | + Mapping udpMapping = new Mapping(Protocol.Udp, port, port, 0, Application.productName + " (UDP)"); |
| 26 | + IPAddress publicIPAddress = null; |
| 27 | + natTask.ContinueWith(tt => |
| 28 | + { |
| 29 | + device = tt.Result; |
| 30 | + device.GetExternalIPAsync() |
| 31 | + .ContinueWith(task => |
| 32 | + { |
| 33 | + publicIPAddress = task.Result; |
| 34 | + return device.CreatePortMapAsync(udpMapping); |
| 35 | + }) |
| 36 | + .Unwrap() |
| 37 | + .ContinueWith(task => |
| 38 | + { |
| 39 | + return device.CreatePortMapAsync(udpMapping); |
| 40 | + }) |
| 41 | + .Unwrap() |
| 42 | + .ContinueWith(task => |
| 43 | + { |
| 44 | + return device.GetAllMappingsAsync(); |
| 45 | + }) |
| 46 | + .Unwrap() |
| 47 | + .ContinueWith(task => |
| 48 | + { |
| 49 | + Mapping[] mappings = task.Result.ToArray(); |
| 50 | + if(mappings.Length == 0) |
| 51 | + { |
| 52 | + if (!invoked) |
| 53 | + callback(false, publicIPAddress); |
| 54 | + invoked = true; |
| 55 | + } |
| 56 | + else |
| 57 | + { |
| 58 | + for (int i = 0; i < mappings.Length; i++) |
| 59 | + { |
| 60 | + if(mappings[i].PrivatePort == port) |
| 61 | + { |
| 62 | + if (!invoked) |
| 63 | + callback(true, publicIPAddress); |
| 64 | + invoked = true; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + }); |
| 69 | + }, TaskContinuationOptions.OnlyOnRanToCompletion); |
| 70 | + |
| 71 | + try |
| 72 | + { |
| 73 | + natTask.Wait(); |
| 74 | + } |
| 75 | + catch (AggregateException e) |
| 76 | + { |
| 77 | + if (e.InnerException is NatDeviceNotFoundException) |
| 78 | + { |
| 79 | + if (!invoked) |
| 80 | + callback(false, publicIPAddress); |
| 81 | + invoked = true; |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments