Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
UPNP
Hérite de : RefCounted < Object
Fonctions Universal Plug and Play (UPnP, litt. "Brancher et jouer Universel") pour la découverte de périphériques, les requêtes et la redirection de port sur un réseau.
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 != UPNP.UPNP_RESULT_SUCCESS:
push_error(str(err))
upnp_completed.emit(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")
upnp_completed.emit(UPNP.UPNP_RESULT_SUCCESS)
func _ready():
thread = Thread.new()
thread.start(_upnp_setup.bind(SERVER_PORT))
func _exit_tree():
# Wait for thread finish here to handle game exit while the thread is running.
thread.wait_to_finish()
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 is a good first stop, the specification can be found at the Open Connectivity Foundation and Godot's implementation is based on the MiniUPnP client.
Propriétés
|
||
|
||
|
Méthodes
void |
add_device(device: UPNPDevice) |
add_port_mapping(port: int, port_internal: int = 0, desc: String = "", proto: String = "UDP", duration: int = 0) const |
|
void |
|
delete_port_mapping(port: int, proto: String = "UDP") const |
|
discover(timeout: int = 2000, ttl: int = 2, device_filter: String = "InternetGatewayDevice") |
|
get_device(index: int) const |
|
get_device_count() const |
|
get_gateway() const |
|
query_external_address() const |
|
void |
remove_device(index: int) |
void |
set_device(index: int, device: UPNPDevice) |
Énumérations
enum UPNPResult: 🔗
UPNPResult UPNP_RESULT_SUCCESS = 0
La commande ou la découverte UPNP a réussi.
UPNPResult UPNP_RESULT_NOT_AUTHORIZED = 1
Non autorisé à utiliser la commande sur le UPNPDevice. Peut être retourné lorsque l'utilisateur a désactivé UPNP sur son routeur.
UPNPResult UPNP_RESULT_PORT_MAPPING_NOT_FOUND = 2
Aucune carte des ports n'a été trouvée pour le port donné, la combinaison de protocole sur le UPNPDevice donné.
UPNPResult UPNP_RESULT_INCONSISTENT_PARAMETERS = 3
Paramètres inconsistants.
UPNPResult UPNP_RESULT_NO_SUCH_ENTRY_IN_ARRAY = 4
Aucune telle entrée dans le tableau. Peut être renvoyé si pour une combinaison de port/protocole donnée n'est pas trouvée sur un UPNPDevice.
UPNPResult UPNP_RESULT_ACTION_FAILED = 5
L’action a échoué.
UPNPResult UPNP_RESULT_SRC_IP_WILDCARD_NOT_PERMITTED = 6
Le UPNPDevice ne permet pas les valeurs joker pour l'adresse IP source.
UPNPResult UPNP_RESULT_EXT_PORT_WILDCARD_NOT_PERMITTED = 7
Les UPNPDevice n'autorisent pas les astérismes pour les ports externes.
UPNPResult UPNP_RESULT_INT_PORT_WILDCARD_NOT_PERMITTED = 8
Les UPNPDevice n'autorisent pas les astérismes pour les ports internes.
UPNPResult UPNP_RESULT_REMOTE_HOST_MUST_BE_WILDCARD = 9
La valeur de l'hôte distante doit être un astérisme.
UPNPResult UPNP_RESULT_EXT_PORT_MUST_BE_WILDCARD = 10
La valeur du port externe doit être un astérisme.
UPNPResult UPNP_RESULT_NO_PORT_MAPS_AVAILABLE = 11
Aucune carte de ports n'est disponible. Peut également être retourné si la fonctionnalité de carte des ports n'est pas disponible.
UPNPResult UPNP_RESULT_CONFLICT_WITH_OTHER_MECHANISM = 12
Est en conflit avec un autre mécanisme. Peut être retourné au lieu de UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING si une carte des ports est en conflit avec une carte existante.
UPNPResult UPNP_RESULT_CONFLICT_WITH_OTHER_MAPPING = 13
Est en conflit avec une carte des ports existante.
UPNPResult UPNP_RESULT_SAME_PORT_VALUES_REQUIRED = 14
Le port externe et interne doivent être les mêmes.
UPNPResult UPNP_RESULT_ONLY_PERMANENT_LEASE_SUPPORTED = 15
Seuls les baux permanents sont pris en charge. N'utilisez pas le paramètre duration lors de l'ajout de carte des ports.
UPNPResult UPNP_RESULT_INVALID_GATEWAY = 16
Passerelle invalide.
UPNPResult UPNP_RESULT_INVALID_PORT = 17
Port invalide.
UPNPResult UPNP_RESULT_INVALID_PROTOCOL = 18
Protocole invalide.
UPNPResult UPNP_RESULT_INVALID_DURATION = 19
Durée non valide.
UPNPResult UPNP_RESULT_INVALID_ARGS = 20
Arguments non valides.
UPNPResult UPNP_RESULT_INVALID_RESPONSE = 21
Réponse invalide.
UPNPResult UPNP_RESULT_INVALID_PARAM = 22
Paramètre invalide.
UPNPResult UPNP_RESULT_HTTP_ERROR = 23
Erreur HTTP.
UPNPResult UPNP_RESULT_SOCKET_ERROR = 24
Erreur de socket.
UPNPResult UPNP_RESULT_MEM_ALLOC_ERROR = 25
Erreur d’allocation de mémoire.
UPNPResult UPNP_RESULT_NO_GATEWAY = 26
Aucune passerelle disponible. Vous pouvez avoir besoin d'appeler discover() d'abord, ou la découverte n'a pas détecté de IGD (InternetGatewayDevices) valide.
UPNPResult UPNP_RESULT_NO_DEVICES = 27
Aucun appareil disponible. Vous pouvez avoir besoin d'appeler discover() d'abord, ou la découverte n'a pas détecté des UPNPDevice valides.
UPNPResult UPNP_RESULT_UNKNOWN_ERROR = 28
Erreur inconnue.
Descriptions des propriétés
Si true, l'IPv6 est utilisée pour la découverte des UPNPDevice.
Si 0, le port local à utiliser pour la découverte est choisi automatiquement par le système. Si 1, la découverte sera faite à partir du port source 1900 (même comme port de destination.) Sinon, la valeur sera utilisée comme port.
String discover_multicast_if = "" 🔗
L'interface multicast à utiliser pour la découverte. Utilise l'interface multicast par défaut si vide.
Descriptions des méthodes
void add_device(device: UPNPDevice) 🔗
Ajouter le UPNPDevice spécifié à la liste des appareils découverts.
int add_port_mapping(port: int, port_internal: int = 0, desc: String = "", proto: String = "UDP", duration: int = 0) const 🔗
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 get_gateway()) 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 get_gateway() and call add_port_mapping() 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 UPNPResult for possible return values.
void clear_devices() 🔗
Efface la liste des appareils découverts.
int delete_port_mapping(port: int, proto: String = "UDP") const 🔗
Deletes the port mapping for the given port and protocol combination on the default gateway (see get_gateway()) 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 UPNPResult for possible return values.
int discover(timeout: int = 2000, ttl: int = 2, device_filter: String = "InternetGatewayDevice") 🔗
Découvre les UPNPDevices locaux. Efface la liste des appareils précédemment découverts.
Filtre pour les appareils de type IGD (InternetGatewayDevice) par défaut, comme ceux gèrent le suivi de port. timeout est la durée d'attente des réponses en millisecondes. ttl est le temps de vie, changez-le seulement si vous savez ce que vous faites.
Voir UPNPResult pour les valeurs de renvoi possibles.
UPNPDevice get_device(index: int) const 🔗
Renvoie l'appareil UPNPDevice à l'index donné.
int get_device_count() const 🔗
Renvoie le nombre de UPNPDevice découverts.
UPNPDevice get_gateway() const 🔗
Renvoie la passerelle par défaut. Il s'agit du premier UPNPDevice découvert qui est également un IGD (InternetGatewayDevice) valide.
String query_external_address() const 🔗
Renvoie l'adresse IP externe de la passerelle par défaut (voir get_gateway()) en tant que chaîne. Renvoie une chaîne vide en cas d'erreur.
void remove_device(index: int) 🔗
Removes the device at index from the list of discovered devices.
void set_device(index: int, device: UPNPDevice) 🔗
Sets the device at index from the list of discovered devices to device.