Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

UPNP

Inherits: RefCounted < Object

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

Description

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 discover and add_port_mapping can return errors that should be checked):

var upnp = UPNP.new()
upnp.discover()
upnp.add_port_mapping(7777)

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

upnp.delete_port_mapping(port)

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

# Emitted when UPnP port mapping setup is completed (regardless of success or failure).
signal upnp_completed(error)

# Replace this with your own server port number between 1024 and 65535.
const SERVER_PORT = 3928
var thread = null

func _upnp_setup(server_port):
    # UPNP queries take some time.
    var upnp = UPNP.new()
    var err = upnp.discover()

    if err != OK:
        push_error(str(err))
        emit_signal("upnp_completed", err)
        return

    if upnp.get_gateway() and upnp.get_gateway().is_valid_gateway():
        upnp.add_port_mapping(server_port, server_port, ProjectSettings.get_setting("application/config/name"), "UDP")
        upnp.add_port_mapping(server_port, server_port, ProjectSettings.get_setting("application/config/name"), "TCP")
        emit_signal("upnp_completed", OK)

func _ready():
    thread