Skip to content
0.2.0-dev Download ZIP
251 lines ·15.2 KB Raw
1<?xml version="1.0" encoding="UTF-8" ?>
2<class name="UPNP" inherits="RefCounted" api_type="core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
3 <brief_description>
4 Universal Plug and Play (UPnP) functions for network device discovery, querying and port forwarding.
5 </brief_description>
6 <description>
7 This class can be used to discover compatible [UPNPDevice]s 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.
8 To forward a specific port (here [code]7777[/code], note both [method discover] and [method add_port_mapping] can return errors that should be checked):
9 [codeblock]
10 var upnp = UPNP.new()
11 upnp.discover()
12 upnp.add_port_mapping(7777)
13 [/codeblock]
14 To close a specific port (e.g. after you have finished using it):
15 [codeblock]
16 upnp.delete_port_mapping(port)
17 [/codeblock]
18 [b]Note:[/b] UPnP discovery blocks the current thread. To perform discovery without blocking the main thread, use [Thread]s like this:
19 [codeblock]
20 # Emitted when UPnP port mapping setup is completed (regardless of success or failure).
21 signal upnp_completed(error)
22
23 # Replace this with your own server port number between 1024 and 65535.
24 const SERVER_PORT = 3928
25 var thread = null
26
27 func _upnp_setup(server_port):
28 # UPNP queries take some time.
29 var upnp = UPNP.new()
30 var err = upnp.discover()
31
32 if err != UPNP.UPNP_RESULT_SUCCESS:
33 push_error(str(err))
34 upnp_completed.emit(err)
35 return
36
37 if upnp.get_gateway() and upnp.get_gateway().is_valid_gateway():
38 upnp.add_port_mapping(server_port, server_port, ProjectSettings.get_setting("application/config/name"), "UDP")
39 upnp.add_port_mapping(server_port, server_port, ProjectSettings.get_setting("application/config/name"), "TCP")
40 upnp_completed.emit(UPNP.UPNP_RESULT_SUCCESS)
41
42 func _ready():
43 thread = Thread.new()
44 thread.start(_upnp_setup.bind(SERVER_PORT))
45
46 func _exit_tree():
47 # Wait for thread finish here to handle game exit while the thread is running.
48 thread.wait_to_finish()
49 [/codeblock]
50 [b]Terminology:[/b] 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".
51 [b]Pitfalls:[/b]
52 - 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!
53 - 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.
54 - 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).
55 - 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.).
56 - 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).
57 [b]Further reading:[/b] If you want to know more about UPnP (and the Internet Gateway Device (IGD) and Port Control Protocol (PCP) specifically), [url=https://en.wikipedia.org/wiki/Universal_Plug_and_Play]Wikipedia[/url] is a good first stop, the specification can be found at the [url=https://openconnectivity.org/developer/specifications/upnp-resources/upnp/]Open Connectivity Foundation[/url] and Godot's implementation is based on the [url=https://github.com/miniupnp/miniupnp]MiniUPnP client[/url].
58 </description>
59 <tutorials>
60 </tutorials>
61 <methods>
62 <method name="add_device">
63 <return type="void" />
64 <param index="0" name="device" type="UPNPDevice" />
65 <description>
66 Adds the given [UPNPDevice] to the list of discovered devices.
67 </description>
68 </method>
69 <method name="add_port_mapping" qualifiers="const">
70 <return type="int" />
71 <param index="0" name="port" type="int" />
72 <param index="1" name="port_internal" type="int" default="0" />
73 <param index="2" name="desc" type="String" default="&quot;&quot;" />
74 <param index="3" name="proto" type="String" default="&quot;UDP&quot;" />
75 <param index="4" name="duration" type="int" default="0" />
76 <description>
77 Adds a mapping to forward the external [param port] (between 1 and 65535, although recommended to use port 1024 or above) on the default gateway (see [method get_gateway]) to the [param port_internal] on the local machine for the given protocol [param proto] (either [code]"TCP"[/code] or [code]"UDP"[/code], 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 [method get_gateway] and call [method add_port_mapping] on it, if any. Note that forwarding a well-known port (below 1024) with UPnP may fail depending on the device.
78 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.
79 If [param port_internal] is [code]0[/code] (the default), the same port number is used for both the external and the internal port (the [param port] value).
80 The description ([param desc]) is shown in some routers management UIs and can be used to point out which application added the mapping.
81 The mapping's lease [param duration] can be limited by specifying a duration in seconds. The default of [code]0[/code] 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 [code]0[/code] (permanent), the allowed range according to spec is between [code]120[/code] (2 minutes) and [code]86400[/code] seconds (24 hours).
82 See [enum UPNPResult] for possible return values.
83 </description>
84 </method>
85 <method name="clear_devices">
86 <return type="void" />
87 <description>
88 Clears the list of discovered devices.
89 </description>
90 </method>
91 <method name="delete_port_mapping" qualifiers="const">
92 <return type="int" />
93 <param index="0" name="port" type="int" />
94 <param index="1" name="proto" type="String" default="&quot;UDP&quot;" />
95 <description>
96 Deletes the port mapping for the given port and protocol combination on the default gateway (see [method get_gateway]) if one exists. [param port] must be a valid port between 1 and 65535, [param proto] can be either [code]"TCP"[/code] or [code]"UDP"[/code]. 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 [enum UPNPResult] for possible return values.
97 </description>
98 </method>
99 <method name="discover">
100 <return type="int" />
101 <param index="0" name="timeout" type="int" default="2000" />
102 <param index="1" name="ttl" type="int" default="2" />
103 <param index="2" name="device_filter" type="String" default="&quot;InternetGatewayDevice&quot;" />
104 <description>
105 Discovers local [UPNPDevice]s. Clears the list of previously discovered devices.
106 Filters for IGD (InternetGatewayDevice) type devices by default, as those manage port forwarding. [param timeout] is the time to wait for responses in milliseconds. [param ttl] is the time-to-live; only touch this if you know what you're doing.
107 See [enum UPNPResult] for possible return values.
108 </description>
109 </method>
110 <method name="get_device" qualifiers="const">
111 <return type="UPNPDevice" />
112 <param index="0" name="index" type="int" />
113 <description>
114 Returns the [UPNPDevice] at the given [param index].
115 </description>
116 </method>
117 <method name="get_device_count" qualifiers="const">
118 <return type="int" />
119 <description>
120 Returns the number of discovered [UPNPDevice]s.
121 </description>
122 </method>
123 <method name="get_gateway" qualifiers="const">
124 <return type="UPNPDevice" />
125 <description>
126 Returns the default gateway. That is the first discovered [UPNPDevice] that is also a valid IGD (InternetGatewayDevice).
127 </description>
128 </method>
129 <method name="query_external_address" qualifiers="const">
130 <return type="String" />
131 <description>
132 Returns the external [IP] address of the default gateway (see [method get_gateway]) as string. Returns an empty string on error.
133 </description>
134 </method>
135 <method name="remove_device">
136 <return type="void" />
137 <param index="0" name="index" type="int" />
138 <description>
139 Removes the device at [param index] from the list of discovered devices.
140 </description>
141 </method>
142 <method name="set_device">
143 <return type="void" />
144 <param index="0" name="index" type="int" />
145 <param index="1" name="device" type="UPNPDevice" />
146 <description>
147 Sets the device at [param index] from the list of discovered devices to [param device].
148 </description>
149 </method>
150 </methods>
151 <members>
152 <member name="discover_ipv6" type="bool" setter="set_discover_ipv6" getter="is_discover_ipv6" default="false">
153 If [code]true[/code], IPv6 is used for [UPNPDevice] discovery.
154 </member>
155 <member name="discover_local_port" type="int" setter="set_discover_local_port" getter="get_discover_local_port" default="0">
156 If [code]0[/code], the local port to use for discovery is chosen automatically by the system. If [code]1[/code], discovery will be done from the source port 1900 (same as destination port). Otherwise, the value will be used as the port.
157 </member>
158 <member name="discover_multicast_if" type="String" setter="set_discover_multicast_if" getter="get_discover_multicast_if" default="&quot;&quot;">
159 Multicast interface to use for discovery. Uses the default multicast interface if empty.
160 </member>
161 </members>
162 <constants>
163 <constant name="UPNP_RESULT_SUCCESS" value="0" enum="UPNPResult">
164 UPNP command or discovery was successful.
165 </constant>
166 <constant name="UPNP_RESULT_NOT_AUTHORIZED" value="1" enum="UPNPResult">
167 Not authorized to use the command on the [UPNPDevice]. May be returned when the user disabled UPNP on their router.
168 </constant>
169 <constant name="UPNP_RESULT_PORT_MAPPING_NOT_FOUND" value="2" enum="UPNPResult">
170 No port mapping was found for the given port, protocol combination on the given [UPNPDevice].
171 </constant>
172 <constant name="UPNP_RESULT_INCONSISTENT_PARAMETERS" value="3" enum="UPNPResult">
173 Inconsistent parameters.
174 </constant>
175 <constant name="UPNP_RESULT_NO_SUCH_ENTRY_IN_ARRAY" value="4" enum="UPNPResult">
176 No such entry in array. May be returned if a given port, protocol combination is not found on a [UPNPDevice].
177 </constant>
178 <constant name="UPNP_RESULT_ACTION_FAILED" value="5" enum="UPNPResult">
179 The action failed.
180 </constant>
181 <constant name="UPNP_RESULT_SRC_IP_WILDCARD_NOT_PERMITTED" value="6" enum="UPNPResult">
182 The [UPNPDevice] does not allow wildcard values for the source IP address.
183 </constant>
184 <constant name="UPNP_RESULT_EXT_PORT_WILDCARD_NOT_PERMITTED" value="7" enum="UPNPResult">
185 The [UPNPDevice] does not allow wildcard values for the external port.
186 </constant>
187 <constant name="UPNP_RESULT_INT_PORT_WILDCARD_NOT_PERMITTED" value="8" enum="UPNPResult">
188 The [UPNPDevice] does not allow wildcard values for the internal port.
189 </constant>
190 <constant name="UPNP_RESULT_REMOTE_HOST_MUST_BE_WILDCARD" value="9" enum="UPNPResult">
191 The remote host value must be a wildcard.
192 </constant>
193 <constant name="UPNP_RESULT_EXT_PORT_MUST_BE_WILDCARD" value="10" enum="UPNPResult">
194 The external port value must be a wildcard.
195 </constant>
196 <constant name="UPNP_RESULT_NO_PORT_MAPS_AVAILABLE" value="11" enum="UPNPResult">
197 No port maps are available. May also be returned if port mapping functionality is not available.
198 </constant>
199 <constant name="UPNP_RESULT_CONFLICT_WITH_OTHER_MECHANISM" value="12" enum="UPNPResult">
200 Conflict with other mechanism. May be returned instead of [constant UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING] if a port mapping conflicts with an existing one.
201 </constant>
202 <constant name="UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING" value="13" enum="UPNPResult">
203 Conflict with an existing port mapping.
204 </constant>
205 <constant name="UPNP_RESULT_SAME_PORT_VALUES_REQUIRED" value="14" enum="UPNPResult">
206 External and internal port values must be the same.
207 </constant>
208 <constant name="UPNP_RESULT_ONLY_PERMANENT_LEASE_SUPPORTED" value="15" enum="UPNPResult">
209 Only permanent leases are supported. Do not use the [code]duration[/code] parameter when adding port mappings.
210 </constant>
211 <constant name="UPNP_RESULT_INVALID_GATEWAY" value="16" enum="UPNPResult">
212 Invalid gateway.
213 </constant>
214 <constant name="UPNP_RESULT_INVALID_PORT" value="17" enum="UPNPResult">
215 Invalid port.
216 </constant>
217 <constant name="UPNP_RESULT_INVALID_PROTOCOL" value="18" enum="UPNPResult">
218 Invalid protocol.
219 </constant>
220 <constant name="UPNP_RESULT_INVALID_DURATION" value="19" enum="UPNPResult">
221 Invalid duration.
222 </constant>
223 <constant name="UPNP_RESULT_INVALID_ARGS" value="20" enum="UPNPResult">
224 Invalid arguments.
225 </constant>
226 <constant name="UPNP_RESULT_INVALID_RESPONSE" value="21" enum="UPNPResult">
227 Invalid response.
228 </constant>
229 <constant name="UPNP_RESULT_INVALID_PARAM" value="22" enum="UPNPResult">
230 Invalid parameter.
231 </constant>
232 <constant name="UPNP_RESULT_HTTP_ERROR" value="23" enum="UPNPResult">
233 HTTP error.
234 </constant>
235 <constant name="UPNP_RESULT_SOCKET_ERROR" value="24" enum="UPNPResult">
236 Socket error.
237 </constant>
238 <constant name="UPNP_RESULT_MEM_ALLOC_ERROR" value="25" enum="UPNPResult">
239 Error allocating memory.
240 </constant>
241 <constant name="UPNP_RESULT_NO_GATEWAY" value="26" enum="UPNPResult">
242 No gateway available. You may need to call [method discover] first, or discovery didn't detect any valid IGDs (InternetGatewayDevices).
243 </constant>
244 <constant name="UPNP_RESULT_NO_DEVICES" value="27" enum="UPNPResult">
245 No devices available. You may need to call [method discover] first, or discovery didn't detect any valid [UPNPDevice]s.
246 </constant>
247 <constant name="UPNP_RESULT_UNKNOWN_ERROR" value="28" enum="UPNPResult">
248 Unknown error.
249 </constant>
250 </constants>
251</class>