UPNPDevice in Godot – Complete Guide

Diving into game development often means dealing with networking and creating multiplayer experiences that players around the world can enjoy together. One aspect developers need to handle when setting up online games is port forwarding, which is where the Universal Plug and Play (UPnP) standard comes into play. With Godot 4, developers have access to a powerful set of UPnP tools directly within their game engine of choice.

What is UPNPDevice?

UPNPDevice is a class available in the Godot 4 engine which provides a straightforward interface for interacting with network devices using the Universal Plug and Play protocol. This class allows you to manage port mappings, typically known as port forwarding, and retrieve network information like local and external IP addresses.

What is it for?

UPNPDevice is particularly useful for multiplayer game developers who need to open up communication ports for their games to work correctly across different networks. Instead of requiring players to manually configure their routers, which can be a technical hurdle, developers can use this class to programmatically manage port forwarding, making the process seamless for the end-user.

Why Should I Learn It?

Understanding how to use the UPNPDevice class empowers you to create more advanced network features in your Godot games. By mastering UPnP, you improve your game’s accessibility and connectivity, greatly enhancing the multiplayer experience. Additionally, learning to automate such a process ensures that your skill-set remains on the cutting edge of game development. Let’s embark on an exploration of how UPNPDevice works with some practical examples.

CTA Small Image

Discovering UPnP Devices

The first step in utilizing UPNPDevice is to discover the UPnP devices on the local network. Godot provides a function for this purpose and allows us to check the availability of these devices with ease.

var upnp = UPNP.new()
if upnp.get_device_count() > 0:
    print("UPnP devices found!")
    print("No UPnP devices found.")

In this example, we have created a new instance of UPNP and called the discover() method, which searches for devices. We then check the number of devices found with get_device_count().

Listing UPnP Devices and Service Info

Once you’ve discovered UPnP devices, you might want to list them and get detailed information about their services.

var upnp = UPNP.new()
for i in range(upnp.get_device_count()):
    var device = upnp.get_device(i)
    print("Device %d: %s" % [i, device.get_description_url()])
    for service in device.get_services():
        print("Service: %s" % service)

This snippet lists all discovered devices, printing out the URL for their description and the services each device offers.

Adding Port Mappings

Next, you will likely want to add a port mapping to allow external traffic to reach your game server. Here’s how you do that using UPNPDevice.

var upnp = UPNP.new()
upnp.add_port_mapping(12345) # This adds a port mapping for port 12345.

The add_port_mapping() method creates a new port mapping for the specified port. In this case, we’re opening port 12345.

Removing Port Mappings

Just as important as adding port mappings is removing them when they are no longer needed. This can be done easily with UPNPDevice.

var upnp = UPNP.new()
upnp.delete_port_mapping(12345) # This removes the port mapping for port 12345.

Here we remove the previously added port mapping for port 12345 using the delete_port_mapping() method.

Retrieving External IP Address

Another common networking task is determining the external IP address of the network. You can do this with UPNPDevice like so:

var upnp = UPNP.new()
var device = upnp.get_device(0) # Assuming at least one device was found
var external_ip = device.query_external_ip()
print("External IP is: %s" % external_ip)

This code retrieves the external IP of the first UPnP device found on the network, which can be useful for displaying connection information for multiplayer sessions.Continuing with our exploration of UPNPDevice functionalities in Godot 4, let’s delve into more varied tasks such as checking the status of port mappings and retrieving specific device information.

Checking the Status of a Port Mapping

Sometimes, you’ll want to verify if a port mapping already exists before attempting to add or remove it. Here’s a method to do that check:

var upnp = UPNP.new()
var port = 12345
if upnp.is_mapped(port):
    print("Port %d is already mapped." % port)
    print("Port %d is not mapped yet." % port)

By calling is_mapped() on the UPNP instance, you can determine if a specific port mapping exists, allowing you to avoid redundant or conflicting configurations.

Retrieving Specific Device Information

The UPnP standard allows devices to share detailed information about themselves. You can retrieve this info using the following methods:

var upnp = UPNP.new()
var device = upnp.get_device(0) # Let's choose the first device

print("Friendly name: %s" % device.get_friendly_name())
print("Manufacturer: %s" % device.get_manufacturer())
print("Model Description: %s" % device.get_model_description())

Using methods like get_friendly_name(), get_manufacturer(), and get_model_description(), developers can easily fetch and display the friendly name, manufacturer details, and the model description of UPnP devices, respectively.

Custom Port Mapping for Different Protocols

Beyond simple port forwarding, UPnP allows you to specify the protocol for your port mappings. This is crucial when working with different network protocols such as TCP or UDP:

var upnp = UPNP.new()
var port = 12345

# Adding a TCP port mapping
upnp.add_port_mapping(port, true, "TCP Port Mapping", "TCP")

# Adding a UDP port mapping
upnp.add_port_mapping(port, true, "UDP Port Mapping", "UDP")

In the presented code, we explicitly specify the protocol for the port mapping by passing “TCP” or “UDP” to the add_port_mapping() method.

Setting Port Mapping Duration

Another aspect of port mapping that developers might want to control is the duration of the mapping. This can be set as follows:

var upnp = UPNP.new()
var port = 12345
var duration = 3600 # Duration in seconds (1 hour)

upnp.add_port_mapping(port, true, "Temporary Port Mapping", "TCP", duration)

Here, we use the add_port_mapping() method while providing an extra argument that sets the duration of the mapping to one hour.

Getting Local IP Address

In networked games, you might need to acquire the local IP address. With the UPNPDevice class, you can get the local IP with ease:

var upnp = UPNP.new()
var device = upnp.get_device(0) # Assuming a device is available
var local_ip = device.get_local_ip()

print("Local IP is: %s" % local_ip)

In this snippet, the get_local_ip() method is used to fetch the local IP address of the device. This information can be used within your game for setting up local multiplayer sessions or for debugging purposes.

Refreshing the UPnP Device List

In dynamic network environments, the set of available UPnP devices can change. It’s important for your game to refresh the devices list occasionally:

var upnp = UPNP.new()

func refresh_upnp_devices():
    upnp.clear_devices() # Clears the existing list of devices
    print("Device list refreshed. Number of devices: %d" % upnp.get_device_count())

# Call this function whenever you need to update the device list

By calling refresh_upnp_devices() you ensure your game works with the most up-to-date network environment, which is essential particularly when players experience network changes or disruptions during gameplay.

These examples demonstrate the flexibility and power the UPNPDevice class offers to game developers using the Godot 4 engine. Leveraging these functionalities can significantly enhance the multiplayer capabilities of your game, providing a more reliable and user-friendly experience.With the basics covered, let’s proceed to explore more advanced features of the UPNPDevice to fine-tune your networking setup in Godot 4.

When implementing multiplayer features, it’s important to manage the network environment for your players carefully. We want to create an experience that is both secure and performs well, and to do that, we often need to go beyond simple port forwarding.

Specifying a Local Device

Sometimes your game server might run on a specific device within a local network with multiple devices. Let’s look at how to specify which local device you’ll be mapping the ports for:

var upnp = UPNP.new()
var local_device_ip = "" # This should be the local IP of your device


This code sets the local IP to a specific device before adding a port mapping. This ensures that the traffic for your port is directed to the correct device on the local network.

Checking for Specific UPnP Features

Not all UPnP devices are created equal. Before trying to interact with a device, it might be a good idea to check if it supports the features you need:

var upnp = UPNP.new()
var device = upnp.get_device(0)

if device.supports_port_mapping():
    print("This device supports port mapping.")
    print("This device does not support port mapping.")

The supports_port_mapping() method checks whether the target device supports port mapping or not, allowing you to handle devices that may not be capable of this feature.

Discover Specific Services

Instead of mapping ports, you might be more interested in filtering devices based on specific services:

var upnp = UPNP.new()
upnp.discover(service_type: "WANIPConnection:1")

for i in range(upnp.get_device_count()):
    var device = upnp.get_device(i)
    print("Device %d offers WAN IP connection services." % i)

We can filter devices offering WAN IP connection services by specifying the service_type parameter in the discover() method.

Setting the Discovery Timeout

Network discovery can take time, and you may need to specify how long your game should wait for devices to respond:

var upnp = UPNP.new()
var timeout = 2000 # The timeout is in milliseconds, so this is 2 seconds.


The set_discover_timeout() method allows developers to set the maximum time for the discovery process, helping to prevent the game from staying in a lengthy discovery state.

By combining these advanced features of the UPNPDevice in Godot 4, you can provide a networking experience that is robust and tailored to your game’s specific multiplayer needs. Understanding and implementing these elements can make sure your game remains well-connected, regardless of the variety and unpredictability of players’ network environments.

When integrating these networking features into your Godot 4 project, remember that networking behaviors can be unpredictable. Always include proper error handling and user feedback to ensure a smooth multiplayer experience. Keep in mind that while UPnP simplifies the process of port forwarding, not all users may have UPnP enabled on their routers or may be behind strict firewalls. It’s always a good idea to provide users with alternative connection options or detailed instructions if automatic configuration fails.

By now, you should have a better grasp of the capabilities that Godot 4 offers through the UPNPDevice. Whether you’re creating a small local multiplayer game or aspiring to build larger-scale online experiences, these tools provide a solid foundation for managing network settings programmatically. Happy coding and game development!

Where to Go Next in Your Godot Game Development Journey

Now that you’ve gotten a taste of how networking with the UPNPDevice class in Godot 4 can enhance your game’s multiplayer experience, it’s natural to wonder about the next steps in your game development journey. Knowledge is power in game creation, and there’s always more to learn and explore. Whether you want to refine your current project or start something entirely new, continuous learning is key to staying ahead in the ever-evolving world of game development.

To keep up the momentum and further expand your game development arsenal, consider enrolling in our Godot Game Development Mini-Degree. This comprehensive collection of courses will guide you through the intricacies of the Godot 4 engine, ranging from the basics to more advanced concepts. You’ll have the opportunity to work on practical projects that solidify your understanding and enhance your portfolio.

For those seeking a broader array of topics or eager to dive deeper into specific areas of Godot, be sure to check out our full catalog of Godot courses. With a diverse selection tailored to different interests and skill levels, you’ll find resources to elevate your skills from beginner to professional. Join us at Zenva and take control of your educational journey to craft the games you’re passionate about with confidence and skill.


In the realms of networking and game development, mastering the use of UPNPDevice within Godot 4 can be the difference between a good and a great multiplayer experience. It’s an invaluable skill set that not only removes barriers for players but also opens up doors for you as a developer to create dynamic, engaging online games. Remember that with the power of Godot’s networking capabilities, you have the potential to connect players in ways that are both seamless and exciting.

As you continue to build and refine your multiplayer games, never stop leveling up your skills. Dive into our Godot Game Development Mini-Degree to discover comprehensive lessons, valuable insights, and hands-on projects that will propel your game development journey forward. Join our community of learners at Zenva, where your next game development adventure awaits!

Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.