/// <summary> /// Get the remote IP of this machine. /// </summary> /// <returns>Returns the remote IP of this machine, else if there is a problem returns Null.</returns> public static string GetRemoteIP() { UpnpPort port = GetInfoUpnpPort(Global.ListeningPort); if (port != null) { return(port.ExternalIP); } else { int nPort = OpenRandomPort(); port = GetInfoUpnpPort(nPort); ClosePort(nPort, Protocol.TCP); if (port != null) { return(port.ExternalIP); } else { return(null); } } }
/// <summary> /// Gets info about a UPnP port. /// </summary> /// <param name="PortNumber">The number of the port to get info.</param> /// <returns>The info about the UPnP port. Return null if is the UPnP port is not exist.</returns> public static UpnpPort GetInfoUpnpPort(int PortNumber) { NATUPNPLib.UPnPNATClass upnpnat = new NATUPNPLib.UPnPNATClass(); NATUPNPLib.IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection; if (mappings != null) { foreach(NATUPNPLib.IStaticPortMapping portMapping in mappings) { if (portMapping.ExternalPort == PortNumber) { UpnpPort port = new UpnpPort(); port.Description = portMapping.Description; port.Enabled = portMapping.Enabled; port.InternalIP = portMapping.InternalClient; port.ExternalIP = portMapping.ExternalIPAddress; port.Port = portMapping.ExternalPort; port.Protocol = (Protocol)Enum.Parse(typeof(Protocol), portMapping.Protocol, true); return port; } } } return null; }
/// <summary> /// Gets info about a UPnP port. /// </summary> /// <param name="PortNumber">The number of the port to get info.</param> /// <returns>The info about the UPnP port. Return null if is the UPnP port is not exist.</returns> public static UpnpPort GetInfoUpnpPort(int PortNumber) { NATUPNPLib.UPnPNATClass upnpnat = new NATUPNPLib.UPnPNATClass(); NATUPNPLib.IStaticPortMappingCollection mappings = upnpnat.StaticPortMappingCollection; if (mappings != null) { foreach (NATUPNPLib.IStaticPortMapping portMapping in mappings) { if (portMapping.ExternalPort == PortNumber) { UpnpPort port = new UpnpPort(); port.Description = portMapping.Description; port.Enabled = portMapping.Enabled; port.InternalIP = portMapping.InternalClient; port.ExternalIP = portMapping.ExternalIPAddress; port.Port = portMapping.ExternalPort; port.Protocol = (Protocol)Enum.Parse(typeof(Protocol), portMapping.Protocol, true); return(port); } } } return(null); }