-
Notifications
You must be signed in to change notification settings - Fork 174
Add NAT traversal via UPnP port mapping #771
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 7 commits
3c2de79
25ff339
30a285b
d7b6e7c
24c4750
4a7e125
9e9a60a
191ced5
c8a12b1
eae7ab1
68adc86
23ebda1
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# UPnP Example | ||
|
||
This example demonstrates how to use the integrated UPnP behaviour to automatically create a port mapping on your local network's gateway (e.g., your home router). | ||
|
||
This allows peers from the public internet to directly dial your node, which is a crucial step for NAT traversal. | ||
|
||
## Usage | ||
|
||
First, ensure you have installed the necessary dependencies from the root of the repository: | ||
|
||
```sh | ||
pip install -e ".[upnp]" | ||
``` | ||
|
||
Then, run the script in a terminal: | ||
|
||
```sh | ||
python examples/upnp/upnp_demo.py | ||
``` | ||
|
||
The script will start a libp2p host and immediately try to discover a UPnP-enabled gateway on the network. | ||
|
||
- If it **succeeds**, it will print the new external address that has been mapped. | ||
- If it **fails** (e.g., your router doesn't have UPnP enabled or you're behind a double NAT), it will print a descriptive error message. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
import argparse | ||
import logging | ||
|
||
import multiaddr | ||
import trio | ||
|
||
from libp2p import new_host | ||
|
||
logging.basicConfig(level=logging.INFO) | ||
logger = logging.getLogger("upnp-demo") | ||
|
||
|
||
async def run(port: int) -> None: | ||
listen_maddr = multiaddr.Multiaddr(f"/ip4/0.0.0.0/tcp/{port}") | ||
host = new_host(enable_upnp=True) | ||
|
||
async with host.run(listen_addrs=[listen_maddr]): | ||
try: | ||
logger.info(f"Host started with ID: {host.get_id().pretty()}") | ||
logger.info(f"Listening on: {host.get_addrs()}") | ||
logger.info("Host is running. Press Ctrl+C to shut down.") | ||
logger.info("If UPnP discovery was successful, ports are now mapped.") | ||
await trio.sleep_forever() | ||
except KeyboardInterrupt: | ||
logger.info("Shutting down...") | ||
finally: | ||
# UPnP teardown is automatic via host.run() | ||
logger.info("Shutdown complete.") | ||
|
||
|
||
def main() -> None: | ||
parser = argparse.ArgumentParser(description="UPnP example for py-libp2p") | ||
parser.add_argument( | ||
"-p", "--port", type=int, default=0, help="Local TCP port (0 for random)" | ||
) | ||
args = parser.parse_args() | ||
|
||
try: | ||
trio.run(run, args.port) | ||
except KeyboardInterrupt: | ||
pass | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
import ipaddress | ||
import logging | ||
|
||
import miniupnpc # type: ignore[import-error] | ||
import trio | ||
|
||
logger = logging.getLogger("libp2p.discovery.upnp") | ||
|
||
|
||
class UpnpManager: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sure , will be adding that asap! |
||
""" | ||
A simple, self-contained manager for UPnP port mapping that can be used | ||
alongside a libp2p Host. | ||
""" | ||
|
||
def __init__(self) -> None: | ||
self._gateway = miniupnpc.UPnP() | ||
self._lan_addr: str | None = None | ||
self._external_ip: str | None = None | ||
|
||
async def discover(self) -> bool: | ||
""" | ||
Discover the UPnP IGD on the network. | ||
|
||
:return: True if a gateway is found, False otherwise. | ||
""" | ||
logger.debug("Discovering UPnP gateway...") | ||
try: | ||
try: | ||
num_devices = await trio.to_thread.run_sync(self._gateway.discover) | ||
except Exception as e: | ||
# The miniupnpc library has a known quirk where `discover()` can | ||
# raise an exception with the message "Success" on some platforms | ||
# (e.g., Windows) instead of returning a number of devices. We treat | ||
# this as a successful discovery of 1 device. | ||
if str(e) == "Success": # type: ignore | ||
num_devices = 1 | ||
else: | ||
logger.exception("UPnP discovery exception") | ||
return False | ||
|
||
if num_devices > 0: | ||
await trio.to_thread.run_sync(self._gateway.selectigd) | ||
self._lan_addr = self._gateway.lanaddr | ||
self._external_ip = await trio.to_thread.run_sync( | ||
self._gateway.externalipaddress | ||
) | ||
logger.debug(f"UPnP gateway found: {self._external_ip}") | ||
|
||
if self._external_ip is None: | ||
logger.error("Gateway did not return an external IP address") | ||
return False | ||
|
||
ip_obj = ipaddress.ip_address(self._external_ip) | ||
if ip_obj.is_private: | ||
logger.warning( | ||
"UPnP gateway has a private IP; you may be behind a double NAT." | ||
) | ||
return False | ||
return True | ||
else: | ||
logger.debug("No UPnP devices found") | ||
return False | ||
except Exception: | ||
logger.exception("UPnP discovery failed") | ||
return False | ||
|
||
async def add_port_mapping(self, port: int, protocol: str = "TCP") -> bool: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. if port <= 0 or port > 65535:
logger.error(f"Invalid port number: {port}")
return False
if port < 1024:
logger.warning(f"Mapping a well-known port: {port} (may fail)") Setting up these kinds of warning for sketchy port numbers in the params, would save computation time in cases of misbehaviour. Also add similar checks to |
||
""" | ||
Request a new port mapping from the gateway. | ||
|
||
:param port: the internal port to map | ||
:param protocol: the protocol to map (TCP or UDP) | ||
:return: True on success, False otherwise | ||
""" | ||
if not 0 < port < 65536: | ||
logger.error(f"Invalid port number for mapping: {port}") | ||
return False | ||
if port < 1024: | ||
logger.warning( | ||
f"Mapping a well-known (privileged) port ({port}) may fail or " | ||
"require root." | ||
) | ||
|
||
if not self._lan_addr: | ||
logger.error( | ||
"Cannot add port mapping: discovery has not been run successfully." | ||
) | ||
return False | ||
|
||
logger.debug(f"Requesting UPnP mapping for {protocol} port {port}...") | ||
try: | ||
await trio.to_thread.run_sync( | ||
lambda: self._gateway.addportmapping( | ||
port, protocol, self._lan_addr, port, "py-libp2p", "" | ||
) | ||
) | ||
logger.info( | ||
f"Successfully mapped external port {self._external_ip}:{port} " | ||
f"to internal port {self._lan_addr}:{port}" | ||
) | ||
return True | ||
except Exception: | ||
logger.exception(f"Failed to map port {port}") | ||
return False | ||
|
||
async def remove_port_mapping(self, port: int, protocol: str = "TCP") -> bool: | ||
""" | ||
Remove an existing port mapping. | ||
|
||
:param port: the external port to unmap | ||
:param protocol: the protocol (TCP or UDP) | ||
:return: True on success, False otherwise | ||
""" | ||
if not 0 < port < 65536: | ||
logger.error(f"Invalid port number for removal: {port}") | ||
return False | ||
|
||
logger.debug(f"Removing UPnP mapping for {protocol} port {port}...") | ||
try: | ||
await trio.to_thread.run_sync( | ||
lambda: self._gateway.deleteportmapping(port, protocol) | ||
) | ||
logger.info(f"Successfully removed mapping for port {port}") | ||
return True | ||
except Exception: | ||
logger.exception(f"Failed to remove mapping for port {port}") | ||
return False | ||
|
||
def get_external_ip(self) -> str | None: | ||
return self._external_ip |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
negotitate_timeout
Should be negotiate_timeoutThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
that was already there so didn't notice , will correct it!