### Install P2PD using pip Source: https://p2pd.readthedocs.io/en/latest/_sources/articles/install This command installs the P2PD package directly from the Python Package Index (PyPI). It's the simplest way to get started and ensures you have the latest stable release. No specific inputs or outputs are required beyond the command itself. ```bash python3 -m pip install p2pd ``` -------------------------------- ### Install P2PD from Source Source: https://p2pd.readthedocs.io/en/latest/_sources/articles/install This snippet outlines the steps to clone the P2PD repository from GitHub, install it in development mode, and then install optional dependencies for testing and server functionalities. This method is useful for developers who want to contribute to P2PD or use its latest features before they are released on PyPI. ```bash git clone https://github.com/robertsdotpm/p2pd.git cd p2pd python3 setup.py develop python3 -m pip install -r optional-test-requirements.txt python3 -m pip install -r optional-server-requirements.txt ``` -------------------------------- ### Start P2PD Interactive Prompt (Python) Source: https://p2pd.readthedocs.io/en/latest/articles/running_examples This command initiates the P2PD interactive prompt, allowing direct execution of asynchronous code. It automatically sets up the event loop and multiprocessing for consistent behavior. Ensure Python 3 is installed and accessible via 'python3'. ```bash python3 -m p2pd ``` ```python P2PD 2.7.9 REPL on Python 3.8 / win32 Loop = selector, Process = spawn Use "await" directly instead of "asyncio.run()". >>> from p2pd import * ``` -------------------------------- ### Python TURN Client Example Source: https://p2pd.readthedocs.io/en/latest/_sources/built/turn This Python script demonstrates how to use the P2PD TURN client. It showcases the basic setup and usage of the TURN client for relaying packets. This example assumes the P2PD library is installed and configured. ```python from p2pd import TURNClient async def main(): # Replace with your TURN server details TURN_HOST = "your_turn_server.com" TURN_PORT = 3478 USERNAME = "your_username" PASSWORD = "your_password" client = TURNClient(TURN_HOST, TURN_PORT, USERNAME, PASSWORD) await client.start() print(f"TURN client started. Relay address: {client.relay_address}") # Example: Sending data through the TURN relay peer_address = ("some_peer_ip", 12345) # Replace with actual peer address message = b"Hello from TURN client!" await client.sendto(message, peer_address) print(f"Sent message to {peer_address} via TURN.") # Keep the client running to receive data # In a real application, you'd have logic here to process incoming data await client.wait_closed() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### P2PD REPL Initialization Example Source: https://p2pd.readthedocs.io/en/latest/_sources/articles/running_examples This Python snippet shows the initial output and setup commands when entering the P2PD interactive prompt. It indicates the Python version, event loop, multiprocessing method, and provides the import statement for P2PD. ```python3 P2PD 2.7.9 REPL on Python 3.8 / win32 Loop = selector, Process = spawn Use "await" directly instead of "asyncio.run()". >>> from p2pd import * ``` -------------------------------- ### P2PD Node Example in Python Source: https://p2pd.readthedocs.io/en/latest/_sources/p2p/nodes This Python script demonstrates the basic setup and usage of a P2PD node, showcasing how to add message handlers for a custom protocol. It serves as a starting point for developing P2P applications with P2PD. ```python from p2pd import Node def handle_message(node, peer_id, message): print(f"Received message from {peer_id}: {message}") # Create a new P2P node node = Node() # Register a message handler for any incoming messages node.add_handler(handle_message) # Start the node and listen for incoming connections node.start() print("P2P node started. Listening for messages...") # Keep the node running (e.g., in a real application, you'd have a loop or other mechanisms) input("Press Enter to stop the node...") # Stop the node gracefully node.stop() print("P2P node stopped.") ``` -------------------------------- ### Run P2PD Interactive Prompt Source: https://p2pd.readthedocs.io/en/latest/_sources/articles/running_examples This command launches the P2PD interactive prompt, which simplifies running asynchronous code by managing the event loop and multiprocessing setup. It allows direct execution of 'await' commands. ```shell python3 -m p2pd ``` -------------------------------- ### Install pip for Python 3.5 Source: https://p2pd.readthedocs.io/en/latest/_sources/articles/install This command downloads the get-pip.py script for Python 3.5, which is necessary for installing pip on older systems where it might not be pre-installed or up-to-date. This script is essential for subsequently installing packages like P2PD. ```bash https://bootstrap.pypa.io/pip/3.5/get-pip.py ``` -------------------------------- ### Python P2PD Subscription Example Source: https://p2pd.readthedocs.io/en/latest/_sources/general/queues This Python code snippet illustrates how to set up message subscriptions using the P2PD library. It shows the process of subscribing to messages, demonstrating the flexibility of message filtering and routing within the P2PD framework. This example is intended to be run within a Python environment where the P2PD library is installed and configured. ```python3 pipe.unsubscribe(SUB_ALL) ``` -------------------------------- ### Install P2PD on Windows XP Source: https://p2pd.readthedocs.io/en/latest/_sources/articles/install This command installs P2PD on Windows XP using Python 3.5. It assumes prior steps like installing necessary Visual C++ redistributables and Python 3.5 have been completed. This is the final step in setting up P2PD on this specific older Windows version. ```bash python.exe -m pip install p2pd ``` -------------------------------- ### P2PD Node with Nickname Example (Python) Source: https://p2pd.readthedocs.io/en/latest/_sources/p2p/nicknames This Python script demonstrates how to set up a P2P node with a nickname. It requires the p2pd library and handles the process of registering and using a nickname for network communication. Ensure the p2pd library is installed. ```python from p2pd import * # Example usage of setting up a node with a nickname # This is a conceptual example and may require specific network configurations # and P2PD setup to run successfully. # Replace with your desired nickname nickname = "my_awesome_node" # Initialize P2PD node (details depend on P2PD library specifics) # node = P2PNode(config) # Register the nickname with the P2PD network # The register_nickname function likely handles key generation, # HTTP requests to name servers, and TLD calculation. # It returns the full nickname including the TLD. # full_nickname = node.register_nickname(nickname) # print(f"Successfully registered nickname: {full_nickname}") # Later, another peer can use this full_nickname to connect: # other_node.connect(full_nickname) # The actual implementation details for P2PD node initialization, # nickname registration, and connection would be found within the P2PD library's # API documentation and the provided examples. ``` -------------------------------- ### P2PD TURN Client Example in Python Source: https://p2pd.readthedocs.io/en/latest/built/turn Demonstrates how to set up and use the P2PD TURN client for UDP packet relaying. It covers initializing interfaces, starting TURN clients, exchanging relay addresses, accepting peers, sending and receiving messages, and closing client connections. The example assumes a TURN server configuration and uses MQTT for address exchange in a real-world scenario. ```python from p2pd import * async def example(): # TURN server config. dest = ("turn1.p2pd.net", 3478) auth = ("", "") # Each interface has a different external IP. # Imagine these are two different computers. a_nic = await Interface("enp0s25") b_nic = await Interface("wlx00c0cab5760d") # Start TURN clients. a_client = await TURNClient(IP4, dest, a_nic, auth, realm=None) b_client = await TURNClient(IP4, dest, b_nic, auth, realm=None) # In practice you will have to exchange these tups via your protocol. # I use MQTT for doing that. See diagram steps (1)(3). a_addr, a_relay = await a_client.get_tups() b_addr, b_relay = await b_client.get_tups() # White list peers for sending to relay address. # See diagram steps (2)(4). await a_client.accept_peer(b_addr, b_relay) await b_client.accept_peer(a_addr, a_relay) # Send a message to Bob at their relay address. # See middle of TURN relay diagram. buf = b"hello bob" for _ in range(0, 3): await a_client.send(buf) # Get msg from Alice from the TURN server. # See middle of TURN relay diagram. msg = await b_client.recv() assert(msg == buf) # Tell server to close resources for our client. await a_client.close() await b_client.close() if __name__ == '__main__': async_test(example) ``` -------------------------------- ### P2PD REST API - Server Startup Source: https://p2pd.readthedocs.io/en/latest/built/rest_api Instructions on how to start the P2PD REST API server. ```APIDOC ## Starting the P2PD REST API Server ### Description Starts the P2PD REST API server on localhost:12333. The server is unsecured and only allows requests from localhost or null origins. ### Command ```bash python3 -m p2pd.rest_api ``` ### Notes - The server listens on `localhost:12333`. - No password is required. - Requests are restricted to origins `127.0.0.1` or `null`. ``` -------------------------------- ### Python P2PD Interface and Pipe Operations Source: https://p2pd.readthedocs.io/en/latest/general/queues This Python example showcases how to use the P2PD library to establish network connections and manage data flow. It demonstrates opening an interface, routing, opening a TCP pipe, sending data, and receiving messages. Requires the 'p2pd' library to be installed. ```python from p2pd import * async def example(): # Start default interface. # Don't bother resolving external addresses. nic = await Interface() # Echo server address. route = await nic.route().bind() echo_dest = ("45.79.112.203", 4242) # Open a connection to the echo server. pipe = await pipe_open(TCP, echo_dest, route) # Send data down the pipe. msg = b"do echo test" await pipe.send(msg + b"\r\n", echo_dest) # Receive data back. data = await pipe.recv(SUB_ALL, 4) assert(msg in data) # Close the sockets. await pipe.close() # Utility function to run an async function. if __name__ == '__main__': async_test(example) ``` -------------------------------- ### Javascript Message Subscription Example - Javascript Source: https://p2pd.readthedocs.io/en/latest/general/index This Javascript snippet shows an example of subscribing to messages. It details how to set up a subscription mechanism, likely within a messaging system or event-driven architecture. This is useful for frontend applications that need to receive real-time updates. ```javascript class MessageManager { constructor() { this.messageCallbacks = []; } addMessageCallback(callback) { if (typeof callback === 'function') { this.messageCallbacks.push(callback); } } removeMessageCallback(callback) { this.messageCallbacks = this.messageCallbacks.filter(cb => cb !== callback); } publishMessage(message) { this.messageCallbacks.forEach(callback => { try { callback(message); } catch (error) { console.error('Error in message callback:', error); } }); } } // Example Usage: const manager = new MessageManager(); const myCallback1 = (msg) => console.log('Callback 1 received:', msg); const myCallback2 = (msg) => console.log('Callback 2 received:', msg.toUpperCase()); manager.addMessageCallback(myCallback1); manager.addMessageCallback(myCallback2); manager.publishMessage('hello world'); manager.removeMessageCallback(myCallback1); manager.publishMessage('another message'); ``` -------------------------------- ### Setup and Run Concurrent P2PD Tests with Pytest Source: https://p2pd.readthedocs.io/en/latest/dev/index Installs necessary Pytest packages for concurrent test execution and runs the tests in parallel. Requires `pytest`, `pytest-asyncio`, and `pytest-xdist`. ```python python3 -m pip install -U pytest python3 -m pip install pytest-asyncio python3 -m pip install pytest-xdist pytest -n 8 ``` -------------------------------- ### Build P2PD Documentation Source: https://p2pd.readthedocs.io/en/latest/dev/index Installs the required Sphinx dependencies and builds the project documentation. The output can be found in the `html` directory after building. ```python python3 -m pip install sphinx python3 -m pip install myst-parser python3 -m pip install sphinx_rtd_theme python3 -m pip install readthedocs-sphinx-search cd docs python3 -m sphinx.cmd.build source html ``` -------------------------------- ### Example Web Framework Usage (Python) Source: https://p2pd.readthedocs.io/en/latest/_sources/built/http_framework This snippet demonstrates the usage of the lightweight web framework, likely involving route definitions and request handling. It's written in Python 3 and serves as a practical example for developers. ```python3 from p2pd import RESTD @RESTD.GET(["cat"]) def cat_meow(cat): return f"The cat says meow! Name: {cat}" @RESTD.POST() def process_data(body): return f"Received data: {body.decode()}" if __name__ == "__main__": RESTD.serve(port=8080) ``` -------------------------------- ### Python HTTP Client: POST Request Example Source: https://p2pd.readthedocs.io/en/latest/_sources/built/http_client Illustrates how to execute an HTTP POST request using the client library. Similar to GET, the 'vars' method can be used to send data in the request body. ```python from py.aio.http import Client async def main(): client = Client('https://example.com') resp = await client.vars({'key': 'value'}).post('/path') print(resp.output) if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### UDP Await Example - Python Source: https://p2pd.readthedocs.io/en/latest/general/index This Python snippet illustrates an example of using UDP with an await pattern. It demonstrates how to send and receive UDP packets asynchronously. This is beneficial for applications requiring non-blocking network I/O for UDP communication. ```python import asyncio async def udp_echo_client(): loop = asyncio.get_running_loop() transport, protocol = await loop.create_datagram_endpoint( lambda: EchoClientProtocol(loop), remote_name=('127.0.0.1', 9999)) try: transport.sendto(b'Hello UDP!') await asyncio.sleep(1) finally: transport.close() class EchoClientProtocol: def __init__(self, loop): self.loop = loop self.transport = None def connection_made(self, transport): self.transport = transport def datagram_received(self, data, addr): print(f"Received {data.decode()} from {addr}") def error_received(self, exc): print(f"Error received: {exc}") def connection_lost(self, exc): print("Connection closed") async def main(): await udp_echo_client() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Perform HTTP GET Request with SSL Source: https://p2pd.readthedocs.io/en/latest/built/http_client Demonstrates a basic asynchronous GET request to Google, including setting up network parameters, handling SSL, and printing the response. It shows how to pass URL query parameters using the `vars` method. ```python from p2pd import * # Every website today seems to want Javascript # but its an example and demonstrates SSL too. async def example(): # Setup HTTP params. addr = ("www.google.com", 443) params = {"q": "lets search!"} path = "/search" conf = dict_child({ "use_ssl": True }, NET_CONF) # Load interface and route to use. nic = await Interface() curl = WebCurl(addr, nic.route(IP4)) # Make the web request. resp = await curl.vars(params).get(path, conf=conf) print(resp.req_buf) print(resp.out) if __name__ == '__main__': async_test(example) ``` -------------------------------- ### P2PD in a Nutshell Example (Python) Source: https://p2pd.readthedocs.io/en/latest/_sources/index This Python code snippet demonstrates the basic usage of the P2PD library, illustrating how to establish peer-to-peer connections and interact with the P2PD network. It showcases the core functionalities for a quick understanding of the library's capabilities. ```python import p2pd async def main(): # Create a P2PD node node = await p2pd.Node.create() print(f"Node created with ID: {node.id}") # Listen for incoming connections await node.listen() print("Node listening for connections...") # Example: connect to another node (replace with actual peer address) # peer_address = ":" # try: # connection = await node.connect(peer_address) # print(f"Connected to peer: {connection.peer_id}") # # Send and receive data (example) # await connection.send(b"Hello, peer!") # data = await connection.recv() # print(f"Received from peer: {data}") # await connection.close() # except Exception as e: # print(f"Failed to connect or communicate with peer: {e}") # Keep the node running (in a real application, you'd have more logic here) await node.join() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### P2PD API: Get Version Information Source: https://p2pd.readthedocs.io/en/latest/_sources/built/rest_api Example cURL command to fetch the P2PD API version. This is a simple GET request to check if the server is running and responsive. It returns a JSON object with author, title, and version. ```bash curl ``` ```json { "author": "Matthew@Roberts.PM", "title": "P2PD", "version": "3.0.0" } ``` -------------------------------- ### Python HTTP Client: Basic GET Request Source: https://p2pd.readthedocs.io/en/latest/_sources/built/http_client Demonstrates how to perform a basic GET request using the HTTP client, including sending GET parameters to a website. The 'vars' method is used for parameter handling. ```python from py.aio.http import Client async def main(): client = Client('https://example.com') resp = await client.vars({'key': 'value'}).get('/path') print(resp.output) if __name__ == '__main__': import asyncio asyncio.run(main()) ``` -------------------------------- ### P2PD Async-Await Connection Example Source: https://p2pd.readthedocs.io/en/latest/p2p/msg_handling Illustrates establishing a P2P connection using async-await with specified connection strategies. It shows sending a message and then receiving a response. Requires the 'p2pd' library. ```python from p2pd import * strategies = [P2P_DIRECT, P2P_REVERSE, P2P_PUNCH] async def example(): node = await P2PNode() pipe = await node.connect("example.peer", strategies=strategies) await pipe.send(b"Hello, world!") buf = await pipe.recv() await node.close() ``` -------------------------------- ### Python Message Subscription Example - Python Source: https://p2pd.readthedocs.io/en/latest/general/index This Python snippet demonstrates an example of subscribing to messages using Python. It outlines a pattern for managing message subscriptions and callbacks, suitable for backend services or applications requiring event handling. This helps in decoupling components by allowing them to communicate via messages. ```python import asyncio from collections import defaultdict class MessageBroker: def __init__(self): self._subscribers = defaultdict(list) self._loop = asyncio.get_event_loop() async def subscribe(self, topic, callback): if callback not in self._subscribers[topic]: self._subscribers[topic].append(callback) print(f"Subscribed to '{topic}'") async def unsubscribe(self, topic, callback): if callback in self._subscribers[topic]: self._subscribers[topic].remove(callback) print(f"Unsubscribed from '{topic}'") async def publish(self, topic, message): print(f"Publishing to '{topic}': {message}") for callback in self._subscribers[topic]: # Use asyncio.create_task to run callbacks concurrently self._loop.create_task(callback(message)) async def subscriber_one(message): print(f"Subscriber One received: {message}") await asyncio.sleep(0.1) # Simulate work async def subscriber_two(message): print(f"Subscriber Two received: {message.upper()}") await asyncio.sleep(0.2) # Simulate work async def main(): broker = MessageBroker() await broker.subscribe('greetings', subscriber_one) await broker.subscribe('greetings', subscriber_two) await broker.publish('greetings', 'hello there') await asyncio.sleep(0.5) # Allow time for callbacks to complete await broker.unsubscribe('greetings', subscriber_one) await broker.publish('greetings', 'goodbye') await asyncio.sleep(0.5) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### P2PD Node with Configuration Example in Python Source: https://p2pd.readthedocs.io/en/latest/_sources/p2p/nodes This Python script illustrates how to configure a P2PD node with specific settings, such as enabling UPnP for improved reachability. It shows how to pass a configuration dictionary during node initialization. ```python from p2pd import Node def handle_message(node, peer_id, message): print(f"Received message from {peer_id}: {message}") # Configuration for the P2P node config = { "upnp": True, # Enable UPnP for automatic port forwarding "nat_pmp": False, # Disable NAT-PMP if not needed "listen_port": 8000, # Specify a custom listening port "bootstrap_nodes": [ # List of initial nodes to connect to "127.0.0.1:8001", "192.168.1.100:8002" ] } # Create a new P2P node with the specified configuration node = Node(config=config) # Register a message handler node.add_handler(handle_message) # Start the node node.start() print(f"P2P node started with UPnP enabled on port {config['listen_port']}.") input("Press Enter to stop the node...") node.stop() print("P2P node stopped.") ``` -------------------------------- ### Start P2PD REST API Server Source: https://p2pd.readthedocs.io/en/latest/_sources/built/rest_api Command to start the P2PD REST API server. The server runs on localhost:12333 and has no password, allowing requests only from localhost or null origins. ```python python3 -m p2pd.rest_api ``` -------------------------------- ### TCP Echo Server Example (Python) Source: https://p2pd.readthedocs.io/en/latest/_sources/general/pipes A Python 3 example demonstrating a simple TCP server using P2PD. Received data is echoed back to the client. Message handlers include sender addressing information and a pipe object for client interaction. ```python import asyncio import p2pd async def handle_client(reader, writer): addr = writer.get_extra_info('peername') print(f"Connection from {addr}") while True: data = await reader.read(100) if not data: break message = data.decode() print(f"Received {message} from {addr}") writer.write(data) await writer.drain() print(f"Sent {message} to {addr}") print(f"Connection closed from {addr}") writer.close() async def main(): server = await asyncio.start_server( handle_client, '127.0.0.1', 8888) addr = server.sockets[0].getsockname() print(f'Serving on {addr}') async with server: await server.serve_forever() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### IPv6 Route Example Source: https://p2pd.readthedocs.io/en/latest/general/interfaces Demonstrates the creation of routes for IPv6 addresses, distinguishing between global and link-local scopes. It highlights that link-local addresses are copied to each route, while global addresses form new routes. -------------------------------- ### Initialize and Load Default Network Interface in Python Source: https://p2pd.readthedocs.io/en/latest/general/interfaces Demonstrates how to start the default network interface using P2PD, load its associated NAT details, and print the interface information. This is a foundational step for network programming in P2PD. ```python from p2pd import * async def example(): # Start the default interface. nic = await Interface() # Load additional NAT details. # Restrict, random port NAT assumed by default. await nic.load_nat() # Show the interface details. print(nic) if __name__ == '__main__': async_test(example) ``` -------------------------------- ### TCP Echo Server Example in P2PD Source: https://p2pd.readthedocs.io/en/latest/general/pipes Demonstrates a simple TCP echo server using P2PD. It sets up a server that echoes received messages back to the client. The example includes client connection, message sending/receiving, assertion for correctness, and proper closing of server and client pipes. ```python from p2pd import * async def msg_cb(msg, client_tup, pipe): await pipe.send(msg, client_tup) async def example(): # Start the server and use msg_cb to process messages. server = await pipe_open(TCP, msg_cb=msg_cb) # Connect to the server. # Use the IP of the route and unused port for the destination. dest = server.sock.getsockname()[0:2] client = await pipe_open(TCP, dest) # Send data to the server and check receipt. msg = b"test msg." await client.send(msg) out = await client.recv() assert(msg == out) # Close both. await client.close() await server.close() # From inside the async REPL. if __name__ == '__main__': async_test(example) ``` -------------------------------- ### List and Load All Available Network Interfaces in Python Source: https://p2pd.readthedocs.io/en/latest/general/interfaces Provides a Python example of how to retrieve a list of all available network interface names on the system and then load the corresponding Interface objects. This helps in identifying and accessing all network adapters. ```python from p2pd import * async def example(): # Returns a list of Interface names. if_names = await list_interfaces() ifs = await load_interfaces(if_names) print(ifs) if __name__ == '__main__': async_test(example) ``` -------------------------------- ### Python netifaces Wrapper Example Source: https://p2pd.readthedocs.io/en/latest/built/netifaces Demonstrates how to use the 'p2pd' wrapper for the 'netifaces' module to retrieve network interface information, including interface names, addresses (IPv4, IPv6), and default gateways. This code requires an event loop to run. ```python from p2pd import * async def example(): netifaces = await init_p2pd() ifs = netifaces.interfaces() # e.g. ['lo0', 'en0'] info = netifaces.ifaddresses('en0') # {18: [{'addr': '8c:...'}], 30: [{'addr': 'fe80::...%en0', # 'netmask': 'ffff:ffff:ffff:ffff::/64', 'flags': 1024}, # {'addr': 'fdf4:1...', 'netmask': 'ffff:ffff:ffff:ffff::/ # 64', 'flags': 1088}], 2: [{'addr': '192.168.21.144', # 'netmask': '255.255.255.0', 'broadcast': '...'}]} gws = netifaces.gateways() # {'default': {2: ('192.168.21.1', 'en0')}, # 2: [('192.168.21.1', 'en0', True)], # 30: [...]} if __name__ == '__main__': async_test(example) ``` -------------------------------- ### UDP Asynchronous Receive Example (Python) Source: https://p2pd.readthedocs.io/en/latest/_sources/general/pipes Illustrates asynchronous UDP communication in Python using P2PD's await capability for receiving messages. This example leverages message queues and allows the event loop to execute other tasks while waiting for UDP packets, handling potential timeouts due to UDP's lack of delivery guarantees. ```python import asyncio import p2pd async def receive_udp_messages(pipe): while True: try: message = await pipe.recv(timeout=1.0) # Set a timeout for recv if message: print(f"Received: {message}") except asyncio.TimeoutError: print("No message received within timeout.") except Exception as e: print(f"An error occurred: {e}") break async def main(): # Assuming 'udp_pipe' is a pre-configured P2PD UDP pipe object # Example: udp_pipe = await p2pd.pipe_open('UDP', conf={'local_port': 9999}) # For demonstration, let's create a placeholder class MockPipe: async def recv(self, timeout=None): await asyncio.sleep(0.5) # Simulate receiving a message after delay return {'data': 'sample udp message'} udp_pipe = MockPipe() print("Starting UDP message listener...") await receive_udp_messages(udp_pipe) if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Python TCP Reverse Connect Example Source: https://p2pd.readthedocs.io/en/latest/_sources/p2p/connect Illustrates the reverse connect method, where the other side initiates the connection back to the current node. This is achieved using MQTT messages and is useful when connectivity is uncertain or UPnP is not enabled on both sides. ```python3 import p2pd # Example usage for reverse connect # Requires an MQTT broker and subscription for reverse connection requests # p2pd.connect(destination_ip, destination_port, method='reverse') ``` -------------------------------- ### Python TCP Direct Connect Example Source: https://p2pd.readthedocs.io/en/latest/_sources/p2p/connect Demonstrates how to establish a direct TCP connection to a destination node. This method is suitable when the destination is directly reachable, potentially leveraging UPnP for NAT traversal or requiring firewall rule configuration. ```python3 import p2pd # Example usage for direct connect # Assumes a destination node is directly reachable # p2pd.connect(destination_ip, destination_port, method='direct') ``` -------------------------------- ### Perform HTTP POST Request with URL Parameters and Body Source: https://p2pd.readthedocs.io/en/latest/built/http_client Illustrates an asynchronous POST request, sending both URL parameters and a request body. This example targets a hypothetical PHP endpoint for data upload. ```python from p2pd import * async def example(): nic = await Interface() addr = ("93.184.215.14", 80) curl = WebCurl(addr, nic.route(IP4)) params = {"action": "upload"} payload = b"Data to POST!" resp = await curl.vars( url_params=params, body=payload ).post("/meow/cat.php") print(resp.out) if __name__ == '__main__': async_test(example) ``` -------------------------------- ### UDP Asynchronous Send and Receive Example in Python Source: https://p2pd.readthedocs.io/en/latest/general/pipes Demonstrates how to use P2PD for asynchronous UDP communication, including sending a STUN request and receiving a response. It highlights the use of `await` for network operations and handles potential timeouts. ```python import binascii from p2pd import * async def example(): # Open a UDP pipe to google's STUN server. pipe = await pipe_open(UDP, ("stun.l.google.com", 19302)) # Random STUN message ID. msg_id = binascii.hexlify(rand_b(12)) # req = req type len magic cookie req_hex = b"0001" + b"0000" + b"2112A442" + msg_id req_buf = binascii.unhexlify(req_hex) # UDP is unreliable -- try up to 3 times. for _ in range(0, 3): # Send STUN bind request and get resp. await pipe.send(req_buf) resp = await pipe.recv() # Timeout -- try again. if resp is None: continue # Show resp -- exit loop. print(resp) break # Cleanup. await pipe.close() if __name__ == '__main__': async_test(example) ``` -------------------------------- ### Establish Bidirectional Relay with HTTP GET Source: https://p2pd.readthedocs.io/en/latest/built/rest_api This example shows how to initiate a bidirectional relay using an HTTP GET request to the '/tunnel/con_name' endpoint. This method establishes a two-way communication channel, allowing data to be sent and received asynchronously. ```http GET /tunnel/con_name HTTP/1.1\r\n Origin: null\r\n\r\n ``` -------------------------------- ### P2PD API: Get Peer Address Source: https://p2pd.readthedocs.io/en/latest/_sources/built/rest_api Example cURL command to retrieve a peer's address. This is used to establish connections to other peers in the P2PD network. The response is a JSON object containing the address and an error code. ```bash curl ``` ```json { "addr": "[0,1.3.3.7,192.168.21.21,58959,3,2,0]-0-looongcatislong", "error": 0 } ``` -------------------------------- ### Build P2PD Documentation with Sphinx Source: https://p2pd.readthedocs.io/en/latest/_sources/dev/index This shows the dependencies required to build the P2PD documentation using Sphinx and provides the command to compile the docs. After building, the documentation can be viewed locally. ```python python3 -m pip install sphinx python3 -m pip install myst-parser python3 -m pip install sphinx_rtd_theme python3 -m pip install readthedocs-sphinx-search # Navigate to the docs directory first cd docs python3 -m sphinx.cmd.build source html # Open html/index.html to view the documentation. ``` -------------------------------- ### Get P2PD API Version Source: https://p2pd.readthedocs.io/en/latest/built/rest_api Fetches the version information of the P2PD API. This is a simple GET request to the /version endpoint. It's useful for verifying the server is running and checking the API version. ```curl curl http://localhost:12333/version ``` -------------------------------- ### TCP Echo Server Example - Python Source: https://p2pd.readthedocs.io/en/latest/general/index This snippet demonstrates a basic TCP echo server implementation in Python. It showcases how to set up a server that listens for incoming connections and echoes back any data received. This is useful for testing network connectivity and understanding basic TCP socket programming. ```python import asyncio async def handle_client(reader, writer): addr = writer.get_extra_info('peername') print(f"Connection from {addr}") while True: data = await reader.read(100) if not data: break message = data.decode() print(f"Received {message} from {addr}") writer.write(data) await writer.drain() print(f"Connection closed {addr}") writer.close() async def main(): server = await asyncio.start_server( handle_client, '127.0.0.1', 8888) addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets) print(f"Serving on {addrs}") async with server: await server.serve_forever() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### P2P Connection with Nickname Example (Python) Source: https://p2pd.readthedocs.io/en/latest/_sources/index This Python snippet illustrates how to connect to other P2PD nodes using registered nicknames. It highlights the process of registering a nickname, obtaining the full connection address (including TLD), and using it to establish a peer-to-peer connection. ```python import p2pd async def main(): # Create and listen on a P2PD node node = await p2pd.Node.create() await node.listen() print(f"Node listening with ID: {node.id}") # Register a nickname for the node my_nickname = "my_awesome_node" await node.register_nickname(my_nickname) print(f"Nickname '{my_nickname}' registered.") # Get the full address including TLD for sharing full_address = node.get_full_address(my_nickname) print(f"Share this address to connect: {full_address}") # Example: Connect to another node using its full address # other_node_full_address = ".@:" # try: # connection = await node.connect(other_node_full_address) # print(f"Successfully connected to {other_node_full_address}") # await connection.close() # except Exception as e: # print(f"Failed to connect to {other_node_full_address}: {e}") # Keep the node running await node.join() if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Run P2PD Unit Tests Source: https://p2pd.readthedocs.io/en/latest/_sources/dev/index This demonstrates the standard method for running P2PD's unit tests using the unittest module. It also includes commands for running individual test files and specific test functions. ```python # Navigate to the tests directory first python3 -m unittest # To run individual files or tests: python3 -m unittest file_name.ClassName.test_func_name ``` -------------------------------- ### Python TCP Hole Punching Example Source: https://p2pd.readthedocs.io/en/latest/_sources/p2p/connect Provides an example of TCP hole punching, a technique that synchronizes connections from both sides to bypass NAT. This method supports connections over the internet, LAN, and various interface configurations, utilizing NAT enumeration and port prediction. ```python3 import p2pd # Example usage for TCP hole punching # Requires synchronized timing for SYN packets to cross routers # p2pd.connect(destination_ip, destination_port, method='hole_punch') ``` -------------------------------- ### P2PD REST API - Get Peer Address Source: https://p2pd.readthedocs.io/en/latest/built/rest_api How to retrieve a peer's address. ```APIDOC ## GET /addr ### Description Retrieves the address of a peer, used for connecting to it. ### Method GET ### Endpoint `/addr` ### Request Example ```bash curl http://localhost:12333/addr ``` ### Response #### Success Response (200) Returns a JSON object containing the peer's address and an error code. - **addr** (string) - The peer's address. - **error** (integer) - An error code (0 typically indicates success). #### Response Example ```json { "addr": "[0,1.3.3.7,192.168.21.21,58959,3,2,0]-0-looongcatislong", "error": 0 } ``` ``` -------------------------------- ### Get Address Source: https://p2pd.readthedocs.io/en/latest/_sources/built/rest_api Retrieves the network address of the current node. This address is used to connect to this peer from other nodes. ```APIDOC ## GET /addr ### Description Retrieves the network address of the current P2PD node. ### Method GET ### Endpoint `/addr` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **addr** (string) - The network address of the node. - **error** (integer) - An error code, 0 indicates success. #### Response Example ```json { "addr": "[0,1.3.3.7,192.168.21.21,58959,3,2,0]-0-looongcatislong", "error": 0 } ``` ``` -------------------------------- ### IPv4 Route Example Output (Text) Source: https://p2pd.readthedocs.io/en/latest/_sources/general/interfaces Illustrates the output format for IPv4 routing information, showing Network Interface Card (NIC) IP addresses and their corresponding external (EXT) IP addresses. This helps in understanding how P2PD maps internal to external IPs. ```text NIC IPs: 192.168.0.20/32 (1 IP) 193.168.0.0/16 (65024 IPs) 7.7.7.7/32 (1 IP) 8.8.0.0/16 (65024 IPs) EXT IPs: 1.3.3.7/32 (1 IP) 8.8.0.0/16 (65024 IPs) --------------------------------------------------------------- Routes: [...20, 193..., 7.7.7.7] -> [1.3.3.7] [8.8.0.0] -> [8.8.0.0] ``` -------------------------------- ### Get Version Source: https://p2pd.readthedocs.io/en/latest/_sources/built/rest_api Retrieves the current version information of the P2PD server. This is a good endpoint to test if the server is running and accessible. ```APIDOC ## GET /version ### Description Retrieves the version information of the P2PD server. ### Method GET ### Endpoint `/version` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **author** (string) - The author of the P2PD project. - **title** (string) - The title of the P2PD project. - **version** (string) - The current version of the P2PD server. #### Response Example ```json { "author": "Matthew@Roberts.PM", "title": "P2PD", "version": "3.0.0" } ``` ``` -------------------------------- ### Look Up Peer Address Source: https://p2pd.readthedocs.io/en/latest/built/rest_api Retrieves the address of a peer connected to the P2PD network. This GET request to the /addr endpoint returns the peer's address information, including an error code. ```curl curl http://localhost:12333/addr ``` -------------------------------- ### P2PD Pipe Routing Example Source: https://p2pd.readthedocs.io/en/latest/general/pipes Illustrates how to link two P2PD pipes to enable message routing between them, creating a two-way relay. This is a fundamental technique used in P2PD for various networking scenarios. ```python pipe_a.add_pipe(pipe_b) pipe_b.add_pipe(pipe_a) # Messages received at pipe_a will be sent down pipe_b. # Messages received at pipe_b will be sent down pipe_a. ``` -------------------------------- ### IPv6 Route Example Output (Text) Source: https://p2pd.readthedocs.io/en/latest/_sources/general/interfaces Demonstrates the output format for IPv6 routing information, detailing NIC IP addresses (including global and link-local scopes) and their associated external IP addresses. This clarifies the mapping of internal IPv6 addresses to external ones. ```text NIC IPS: 2020:DEED:BEEF::0000/128 (global scope) (1 IP) 2020:DEED:DEED::0000/64 (global scope) (a lot of IPs) FE80:DEED:BEEF::0000/128 (link-local) (1 IP) EXT IPS: 2020:DEED:BEEF::0000/128 (global scope) (1 IP) 2020:DEED:DEED::0000/64 (global scope) (a lot of IPs) --------------------------------------------------------------- Routes: [FE80:DEED:BEEF::0000/128] -> [2020:DEED:BEEF::0000/128] ``` -------------------------------- ### Run P2PD Tests Concurrently with Pytest Source: https://p2pd.readthedocs.io/en/latest/_sources/dev/index This snippet shows how to install the necessary pytest packages for concurrent test execution and then run the tests in parallel. It's intended to speed up the testing process. ```python python3 -m pip install -U pytest python3 -m pip install pytest-asyncio python3 -m pip install pytest-xdist pytest -n 8 ``` -------------------------------- ### Python UDP TURN Relaying Example Source: https://p2pd.readthedocs.io/en/latest/_sources/p2p/connect Demonstrates the use of TURN relaying for UDP traffic, a last-resort method for peer-to-peer connections when other options fail. TURN servers act as intermediaries, relaying all traffic between peers, which introduces centralization and potential ordering issues for UDP data. ```python3 import p2pd # Example usage for TURN relaying # This method is primarily for UDP and used when other methods fail # p2pd.connect(destination_ip, destination_port, method='turn') ``` -------------------------------- ### Send Text Data Source: https://p2pd.readthedocs.io/en/latest/built/rest_api Sends a predefined text string to a connected peer. This example uses the /send resource with a connection name and the string to be sent. The response indicates the number of bytes sent. ```curl curl http://localhost:12333/send/con_name/long_p2pd_test_string_abcd123 ```