reckfellENGINE

Upnp

Universal Plug and Play (UPnP) functions for network device discovery, querying and port forwarding.

On this page
class UpnpReckfellSharpInherits RefCounted

Universal Plug and Play (UPnP) functions for network device discovery, querying and port forwarding.

This class can be used to discover compatible UpnpDevices on the local network and execute commands on them, like managing port mappings (for port forwarding/NAT traversal) and querying the local and remote network IP address. Note that methods on this class are synchronous and block the calling thread. To forward a specific port (here 7777, note both Upnp.Discover and Upnp.AddPortMapping can return errors that should be checked):

To close a specific port (e.g. after you have finished using it):

Text
upnp.delete_port_mapping(port)

Note: UPnP discovery blocks the current thread. To perform discovery without blocking the main thread, use ReckfellThreads like this:

Terminology: In the context of UPnP networking, "gateway" (or "internet gateway device", short IGD) refers to network devices that allow computers in the local network to access the internet ("wide area network", WAN). These gateways are often also called "routers". Pitfalls:

  • As explained above, these calls are blocking and shouldn't be run on the main thread, especially as they can block for multiple seconds at a time. Use threading!
  • Networking is physical and messy. Packets get lost in transit or get filtered, addresses, free ports and assigned mappings change, and devices may leave or join the network at any time. Be mindful of this, be diligent when checking and handling errors, and handle these gracefully if you can: add clear error UI, timeouts and re-try handling.
  • Port mappings may change (and be removed) at any time, and the remote/external IP address of the gateway can change likewise. You should consider re-querying the external IP and try to update/refresh the port mapping periodically (for example, every 5 minutes and on networking failures).
  • Not all devices support UPnP, and some users disable UPnP support. You need to handle this (e.g. documenting and requiring the user to manually forward ports, or adding alternative methods of NAT traversal, like a relay/mirror server, or NAT hole punching, STUN/TURN, etc.).
  • Consider what happens on mapping conflicts. Maybe multiple users on the same network would like to play your game at the same time, or maybe another application uses the same port. Make the port configurable, and optimally choose a port automatically (re-trying with a different port on failure). Further reading: If you want to know more about UPnP (and the Internet Gateway Device (IGD) and Port Control Protocol (PCP) specifically), Wikipedia(https://en.wikipedia.org/wiki/Universal_Plug_and_Play) is a good first stop, the specification can be found at the Open Connectivity Foundation and Reckfell's implementation is based on the MiniUPnP client.

Declarations checked against C# SDK 1.0.0. Expand a name to see declarations and documentation.

Constructors1

UpnpConstructor
# Upnp
C#
public Upnp();

Properties3

DiscoverIpv6Property
# DiscoverIpv6
C#
public bool DiscoverIpv6 { get; set; }

If true, IPv6 is used for UpnpDevice discovery.

DiscoverLocalPortProperty
# DiscoverLocalPort
C#
public int DiscoverLocalPort { get; set; }

If 0, the local port to use for discovery is chosen automatically by the system. If 1, discovery will be done from the source port 1900 (same as destination port). Otherwise, the value will be used as the port.

DiscoverMulticastIfProperty
# DiscoverMulticastIf
C#
public string DiscoverMulticastIf { get; set; }

Multicast interface to use for discovery. Uses the default multicast interface if empty.

Methods17

AddDevicevoid
# AddDevice
C#
public void AddDevice(UpnpDevice device);

Adds the given UpnpDevice to the list of discovered devices.

Parameters
NameTypeDefault
deviceUpnpDevice—
AddPortMappingint
# AddPortMapping
C#
public int AddPortMapping(int port, int portInternal = 0, string desc = "", string proto = "UDP", int duration = 0);

Adds a mapping to forward the external port (between 1 and 65535, although recommended to use port 1024 or above) on the default gateway (see Upnp.GetGateway) to the port_internal on the local machine for the given protocol proto (either "TCP" or "UDP", with UDP being the default). If a port mapping for the given port and protocol combination already exists on that gateway device, this method tries to overwrite it. If that is not desired, you can retrieve the gateway manually with Upnp.GetGateway and call Upnp.AddPortMapping on it, if any. Note that forwarding a well-known port (below 1024) with UPnP may fail depending on the device. Depending on the gateway device, if a mapping for that port already exists, it will either be updated or it will refuse this command due to that conflict, especially if the existing mapping for that port wasn't created via UPnP or points to a different network address (or device) than this one. If port_internal is 0 (the default), the same port number is used for both the external and the internal port (the port value). The description (desc) is shown in some routers management UIs and can be used to point out which application added the mapping. The mapping's lease duration can be limited by specifying a duration in seconds. The default of 0 means no duration, i.e. a permanent lease and notably some devices only support these permanent leases. Note that whether permanent or not, this is only a request and the gateway may still decide at any point to remove the mapping (which usually happens on a reboot of the gateway, when its external IP address changes, or on some models when it detects a port mapping has become inactive, i.e. had no traffic for multiple minutes). If not 0 (permanent), the allowed range according to spec is between 120 (2 minutes) and 86400 seconds (24 hours). See Upnp.UpnpResult for possible return values.

Parameters
NameTypeDefault
portint—
portInternalint0
descstring""
protostring"UDP"
durationint0
Returns int
ClearDevicesvoid
# ClearDevices
C#
public void ClearDevices();

Clears the list of discovered devices.

DeletePortMappingint
# DeletePortMapping
C#
public int DeletePortMapping(int port, string proto = "UDP");

Deletes the port mapping for the given port and protocol combination on the default gateway (see Upnp.GetGateway) if one exists. port must be a valid port between 1 and 65535, proto can be either "TCP" or "UDP". May be refused for mappings pointing to addresses other than this one, for well-known ports (below 1024), or for mappings not added via UPnP. See Upnp.UpnpResult for possible return values.

Parameters
NameTypeDefault
portint—
protostring"UDP"
Returns int
Discoverint
# Discover
C#
public int Discover(int timeout = 2000, int ttl = 2, string deviceFilter = "InternetGatewayDevice");

Discovers local UpnpDevices. Clears the list of previously discovered devices. Filters for IGD (InternetGatewayDevice) type devices by default, as those manage port forwarding. timeout is the time to wait for responses in milliseconds. ttl is the time-to-live; only touch this if you know what you're doing. See Upnp.UpnpResult for possible return values.

Parameters
NameTypeDefault
timeoutint2000
ttlint2
deviceFilterstring"InternetGatewayDevice"
Returns int
GetDeviceUpnpDevice
# GetDevice
C#
public UpnpDevice GetDevice(int index);

Returns the UpnpDevice at the given index.

Parameters
NameTypeDefault
indexint—
Returns UpnpDevice
GetDeviceCountint
# GetDeviceCount
C#
public int GetDeviceCount();

Returns the number of discovered UpnpDevices.

Returns int
GetDiscoverLocalPortint
# GetDiscoverLocalPort
C#
public int GetDiscoverLocalPort();
Returns int
GetDiscoverMulticastIfstring
# GetDiscoverMulticastIf
C#
public string GetDiscoverMulticastIf();
Returns string
GetGatewayUpnpDevice
# GetGateway
C#
public UpnpDevice GetGateway();

Returns the default gateway. That is the first discovered UpnpDevice that is also a valid IGD (InternetGatewayDevice).

Returns UpnpDevice
IsDiscoverIpv6bool
# IsDiscoverIpv6
C#
public bool IsDiscoverIpv6();
Returns bool
QueryExternalAddressstring
# QueryExternalAddress
C#
public string QueryExternalAddress();

Returns the external IP address of the default gateway (see Upnp.GetGateway) as string. Returns an empty string on error.

Returns string
RemoveDevicevoid
# RemoveDevice
C#
public void RemoveDevice(int index);

Removes the device at index from the list of discovered devices.

Parameters
NameTypeDefault
indexint—
SetDevicevoid
# SetDevice
C#
public void SetDevice(int index, UpnpDevice device);

Sets the device at index from the list of discovered devices to device.

Parameters
NameTypeDefault
indexint—
deviceUpnpDevice—
SetDiscoverIpv6void
# SetDiscoverIpv6
C#
public void SetDiscoverIpv6(bool ipv6);
Parameters
NameTypeDefault
ipv6bool—
SetDiscoverLocalPortvoid
# SetDiscoverLocalPort
C#
public void SetDiscoverLocalPort(int port);
Parameters
NameTypeDefault
portint—
SetDiscoverMulticastIfvoid
# SetDiscoverMulticastIf
C#
public void SetDiscoverMulticastIf(string mIf);
Parameters
NameTypeDefault
mIfstring—

Upnp.UpnpResult

ValueDescription
ActionFailed = 5

The action failed.

ConflictWithOtherMapping = 13

Conflict with an existing port mapping.

ConflictWithOtherMechanism = 12

Conflict with other mechanism. May be returned instead of Upnp.UpnpResult.ConflictWithOtherMapping if a port mapping conflicts with an existing one.

ExtPortMustBeWildcard = 10

The external port value must be a wildcard.

ExtPortWildcardNotPermitted = 7

The UpnpDevice does not allow wildcard values for the external port.

HttpError = 23

HTTP error.

InconsistentParameters = 3

Inconsistent parameters.

IntPortWildcardNotPermitted = 8

The UpnpDevice does not allow wildcard values for the internal port.

InvalidArgs = 20

Invalid arguments.

InvalidDuration = 19

Invalid duration.

InvalidGateway = 16

Invalid gateway.

InvalidParam = 22

Invalid parameter.

InvalidPort = 17

Invalid port.

InvalidProtocol = 18

Invalid protocol.

InvalidResponse = 21

Invalid response.

MemAllocError = 25

Error allocating memory.

NoDevices = 27

No devices available. You may need to call Upnp.Discover first, or discovery didn't detect any valid UpnpDevices.

NoGateway = 26

No gateway available. You may need to call Upnp.Discover first, or discovery didn't detect any valid IGDs (InternetGatewayDevices).

NoPortMapsAvailable = 11

No port maps are available. May also be returned if port mapping functionality is not available.

NoSuchEntryInArray = 4

No such entry in array. May be returned if a given port, protocol combination is not found on a UpnpDevice.

NotAuthorized = 1

Not authorized to use the command on the UpnpDevice. May be returned when the user disabled UPNP on their router.

OnlyPermanentLeaseSupported = 15

Only permanent leases are supported. Do not use the duration parameter when adding port mappings.

PortMappingNotFound = 2

No port mapping was found for the given port, protocol combination on the given UpnpDevice.

RemoteHostMustBeWildcard = 9

The remote host value must be a wildcard.

SamePortValuesRequired = 14

External and internal port values must be the same.

SocketError = 24

Socket error.

SrcIPWildcardNotPermitted = 6

The UpnpDevice does not allow wildcard values for the source IP address.

Success = 0

UPNP command or discovery was successful.

UnknownError = 28

Unknown error.

Reckfell Engine documentationBack to top ↑
QUICK LINKSGetting startedEntity hierarchyC# & .NET 10Scenes and prefabs
Reckfell guides and full API K
reckfellENGINE
RECKFELL ACCOUNT

Sign in

Sign in to your Reckfell account.

One account for the entire Reckfell platform.