### Define Executables and Installation Rules Source: https://github.com/miniupnp/libnatpmp/blob/master/CMakeLists.txt This section defines the build targets for executables like natpmpc and testgetgateway, and specifies the installation paths for the library, headers, and pkg-config files. ```cmake add_executable(natpmpc natpmpc.c) target_link_libraries(natpmpc natpmp) add_executable(testgetgateway testgetgateway.c getgateway.c) target_link_libraries(testgetgateway natpmp) install(TARGETS natpmp natpmpc RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(FILES natpmp.h natpmp_declspec.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) ``` -------------------------------- ### Java NAT-PMP Client for Public IP Address Retrieval Source: https://context7.com/miniupnp/libnatpmp/llms.txt A Java example demonstrating the use of the libnatpmp Java API to retrieve the public IP address of the network. It includes logic for sending the request, retrying responses, and handling potential errors. ```Java import java.net.InetAddress; import java.net.UnknownHostException; import fr.free.miniupnp.libnatpmp.NatPmp; import fr.free.miniupnp.libnatpmp.NatPmpResponse; public class NatPmpExample { public static void main(String[] args) { // Create NAT-PMP client NatPmp natpmp = new NatPmp(); NatPmpResponse response = new NatPmpResponse(); // Request public IP address natpmp.sendPublicAddressRequest(); // Wait for response with retry logic int result; do { result = natpmp.readNatPmpResponseOrRetry(response); if (result == -100) { // NATPMP_TRYAGAIN try { Thread.sleep(250); // Wait before retry } catch (InterruptedException e) { // Continue } } else if (result < 0) { throw new RuntimeException("NAT-PMP error: " + result); } } while (result == -100); // Convert address to InetAddress try { byte[] bytes = intToByteArray(response.addr); InetAddress publicAddr = InetAddress.getByAddress(bytes); System.out.println("Public IP: " + publicAddr.getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } } // Helper to convert int to byte array (little-endian) private static byte[] intToByteArray(int value) { return new byte[] { (byte)value, (byte)(value >>> 8), (byte)(value >>> 16), (byte)(value >>> 24) }; } } ``` -------------------------------- ### NAT-PMP Client Utility (Bash) Source: https://context7.com/miniupnp/libnatpmp/llms.txt A command-line interface tool for interacting with NAT-PMP. It allows users to query public IP addresses, add/remove port mappings for TCP and UDP protocols, and specify a gateway. Usage examples demonstrate common operations. ```bash # Display public IP address natpmpc # Output: # initnatpmp() returned 0 (SUCCESS) # using gateway : 192.168.1.1 # sendpublicaddressrequest returned 2 (SUCCESS) # readnatpmpresponseorretry returned 0 (OK) # Public IP address : 203.0.113.45 # epoch = 123456 # Add TCP port mapping: public 8080 -> private 80, lifetime 3600 seconds natpmpc -a 8080 80 tcp 3600 # Output: # Mapped public port 8080 protocol TCP to local port 80 lifetime 3600 # Add UDP port mapping natpmpc -a 5000 5000 udp 7200 # Delete a port mapping (set lifetime to 0) natpmpc -a 8080 80 tcp 0 # Delete all mappings for this machine (ports and lifetime = 0) natpmpc -a 0 0 tcp 0 # Use a specific gateway instead of auto-detection natpmpc -g 192.168.1.1 natpmpc -g 192.168.1.1 -a 8080 80 tcp 3600 ``` -------------------------------- ### Get NAT-PMP Error String (C) Source: https://context7.com/miniupnp/libnatpmp/llms.txt Provides a human-readable string representation of NAT-PMP error codes. This functionality is conditional and requires the ENABLE_STRNATPMPERR macro to be defined during compilation. It maps integer error codes to descriptive messages. ```c #include #include "natpmp.h" void print_error(int error_code) { #ifdef ENABLE_STRNATPMPERR printf("Error %d: %s\n", error_code, strnatpmperr(error_code)); #else printf("Error %d (strnatpmperr not enabled)\n", error_code); #endif } /* Error codes and messages: * -1 = invalid arguments * -2 = socket() failed * -3 = cannot get default gateway ip address * -4 = close()/closesocket() failed * -5 = recvfrom() failed * -6 = no pending request * -7 = the gateway does not support nat-pmp * -8 = connect() failed * -9 = packet not received from the default gateway * -10 = send() failed * -11 = fcntl() failed * -12 = gettimeofday() failed * -14 = unsupported nat-pmp version error from server * -15 = unsupported nat-pmp opcode error from server * -49 = undefined nat-pmp server error * -51 = not authorized * -52 = network failure * -53 = nat-pmp server out of resources */ ``` -------------------------------- ### Get NAT-PMP Request Timeout (C) Source: https://context7.com/miniupnp/libnatpmp/llms.txt Retrieves the timeout value for the current NAT-PMP request, implementing exponential backoff. It indicates the current retry attempt and the maximum number of retries allowed. Dependencies include standard C libraries and natpmp.h. ```c #include #include #include "natpmp.h" void print_timeout_info(natpmp_t *natpmp) { struct timeval timeout; int r; r = getnatpmprequesttimeout(natpmp, &timeout); if (r == 0) { printf("Current timeout: %ld.%06ld seconds\n", (long)timeout.tv_sec, (long)timeout.tv_usec); printf("Retry attempt: %d of %d\n", natpmp->try_number, NATPMP_MAX_RETRIES); } else if (r == NATPMP_ERR_NOPENDINGREQ) { printf("No pending request\n"); } } /* Timeout progression (per RFC 6886): * Attempt 1: 250ms * Attempt 2: 500ms * Attempt 3: 1000ms * Attempt 4: 2000ms * ... * Maximum total wait: ~127.75 seconds */ ``` -------------------------------- ### Building libnatpmp Library and Tools Source: https://context7.com/miniupnp/libnatpmp/llms.txt Provides compilation commands for building the libnatpmp library and associated tools on various platforms including Unix-like systems, Windows with Visual Studio, and MinGW. It covers options for static and shared libraries, Python module build, and CMake usage. ```Bash # Build library and client tool on Unix/Linux/macOS make # Build with error string support make CFLAGS="-DENABLE_STRNATPMPERR" # Build static library only make libnatpmp.a # Build shared library make libnatpmp.so # Install to system directories sudo make install # Build Python module python setup.py build python setup.py install # Build with CMake (cross-platform) mkdir build && cd build cmake .. make # Build on Windows with Visual Studio # Open msvc/natpmp.sln or use: build.bat # Build on Windows with MinGW make -f Makefile.mingw ``` -------------------------------- ### Create and Delete Port Mappings with libnatpmp Source: https://context7.com/miniupnp/libnatpmp/llms.txt Demonstrates how to initiate a new port mapping request using sendnewportmappingrequest. It also shows how to delete specific mappings by setting the lifetime to zero and how to clear all host mappings. ```c #include #include #include #include #include "natpmp.h" int main() { natpmp_t natpmp; natpmpresp_t response; int r; struct timeval timeout; fd_set fds; initnatpmp(&natpmp, 0, 0); r = sendnewportmappingrequest(&natpmp, NATPMP_PROTOCOL_TCP, 80, 8080, 3600); printf("sendnewportmappingrequest returned %d (%s)\n", r, r == 12 ? "SUCCESS" : "FAILED"); do { FD_ZERO(&fds); FD_SET(natpmp.s, &fds); getnatpmprequesttimeout(&natpmp, &timeout); select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(&natpmp, &response); } while (r == NATPMP_TRYAGAIN); if (r == 0) { printf("Mapped public port %u to local port %u\n", response.pnu.newportmapping.mappedpublicport, response.pnu.newportmapping.privateport); printf("Lifetime: %u seconds\n", response.pnu.newportmapping.lifetime); } sendnewportmappingrequest(&natpmp, NATPMP_PROTOCOL_TCP, 80, 8080, 0); sendnewportmappingrequest(&natpmp, NATPMP_PROTOCOL_TCP, 0, 0, 0); closenatpmp(&natpmp); return 0; } ``` -------------------------------- ### Python Port Mapping Operations with libnatpmp Source: https://context7.com/miniupnp/libnatpmp/llms.txt Demonstrates how to add and delete port mappings using the Python bindings for libnatpmp. It includes error handling for failed operations and shows how to retrieve the mapped public port. ```Python import natpmp # Add port mapping: (external_port, protocol, internal_port, lifetime) try: mapped_port = natpmp.addportmapping(8080, "TCP", 80, 3600) print(f"Mapped to public port: {mapped_port}") except Exception as e: print(f"Failed to add mapping: {e}") # Add UDP port mapping mapped_port = natpmp.addportmapping(5000, "UDP", 5000, 7200) # Delete port mapping: (external_port, protocol, internal_port) try: natpmp.deleteportmapping(8080, "TCP", 80) print("Mapping deleted") except Exception as e: print(f"Failed to delete mapping: {e}") ``` -------------------------------- ### Configure libnatpmp Build System Source: https://github.com/miniupnp/libnatpmp/blob/master/CMakeLists.txt This CMake configuration defines the project metadata, source files, and library compilation settings. It includes conditional logic to handle platform-specific dependencies like WinSock and IPHLPAPI for Windows, or network libraries for Haiku. ```cmake cmake_minimum_required(VERSION 3.5) file(STRINGS VERSION PVER) project(natpmp LANGUAGES C VERSION ${PVER} DESCRIPTION "A portable and fully compliant implementation of the NAT-PMP protocol" HOMEPAGE_URL "https://github.com/miniupnp/libnatpmp") set (NATPMP_SOURCES natpmp.c getgateway.c) if (WIN32) set (NATPMP_SOURCES ${NATPMP_SOURCES} wingettimeofday.c) endif (WIN32) add_library(natpmp ${NATPMP_SOURCES}) target_include_directories(natpmp PUBLIC ${CMAKE_CURRENT_LIST_DIR}) target_compile_definitions(natpmp PRIVATE -DENABLE_STRNATPMPERR) if (WIN32) target_link_libraries(natpmp PUBLIC ws2_32 iphlpapi) if (BUILD_SHARED_LIBS) target_compile_definitions(natpmp PUBLIC -DNATPMP_EXPORTS) else() target_compile_definitions(natpmp PUBLIC -DNATPMP_STATICLIB) endif (BUILD_SHARED_LIBS) endif (WIN32) ``` -------------------------------- ### Initialize NAT-PMP Session (C) Source: https://context7.com/miniupnp/libnatpmp/llms.txt Initializes a NAT-PMP session using the libnatpmp library. It creates a UDP socket and connects to the default gateway, with an option to specify a gateway address. The function returns 0 on success and negative error codes on failure. ```c #include #include #include #include "natpmp.h" int main() { natpmp_t natpmp; int r; /* Initialize with auto-detected gateway */ r = initnatpmp(&natpmp, 0, 0); if (r < 0) { fprintf(stderr, "initnatpmp() failed: %d\n", r); return 1; } /* Print the gateway being used */ struct in_addr gateway_addr; gateway_addr.s_addr = natpmp.gateway; printf("Connected to gateway: %s\n", inet_ntoa(gateway_addr)); /* Or initialize with a specific gateway */ natpmp_t natpmp_forced; in_addr_t forced_gateway = inet_addr("192.168.1.1"); r = initnatpmp(&natpmp_forced, 1, forced_gateway); /* forcegw=1 */ closenatpmp(&natpmp); closenatpmp(&natpmp_forced); return 0; } /* Return values: * 0 = SUCCESS * NATPMP_ERR_INVALIDARGS (-1) * NATPMP_ERR_SOCKETERROR (-2) * NATPMP_ERR_CANNOTGETGATEWAY (-3) * NATPMP_ERR_FCNTLERROR (-11) * NATPMP_ERR_CONNECTERR (-8) */ ``` -------------------------------- ### NAT-PMP Initialization API Source: https://context7.com/miniupnp/libnatpmp/llms.txt Initializes a NAT-PMP session, establishing a connection to the default or a specified gateway. This function sets up the necessary structures and sockets for subsequent NAT-PMP operations. ```APIDOC ## initnatpmp - Initialize NAT-PMP Session ### Description Initializes a NAT-PMP session object, creating a UDP socket and connecting to the default gateway (or a specified gateway). The function automatically detects the default gateway unless forcegw is set to 1, in which case forcedgw is used as the gateway address. ### Method C Function Call ### Endpoint N/A (Local Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c #include #include #include #include "natpmp.h" int main() { natpmp_t natpmp; int r; /* Initialize with auto-detected gateway */ r = initnatpmp(&natpmp, 0, 0); if (r < 0) { fprintf(stderr, "initnatpmp() failed: %d\n", r); return 1; } /* Print the gateway being used */ struct in_addr gateway_addr; gateway_addr.s_addr = natpmp.gateway; printf("Connected to gateway: %s\n", inet_ntoa(gateway_addr)); /* Or initialize with a specific gateway */ natpmp_t natpmp_forced; in_addr_t forced_gateway = inet_addr("192.168.1.1"); r = initnatpmp(&natpmp_forced, 1, forced_gateway); /* forcegw=1 */ closenatpmp(&natpmp); closenatpmp(&natpmp_forced); return 0; } ``` ### Response #### Success Response (0) Initialization successful. #### Response Example Return values: * 0 = SUCCESS * NATPMP_ERR_INVALIDARGS (-1) * NATPMP_ERR_SOCKETERROR (-2) * NATPMP_ERR_CANNOTGETGATEWAY (-3) * NATPMP_ERR_FCNTLERROR (-11) * NATPMP_ERR_CONNECTERR (-8) ``` -------------------------------- ### Python NAT-PMP Client (Python) Source: https://context7.com/miniupnp/libnatpmp/llms.txt An object-oriented Python wrapper for the libnatpmp library, simplifying NAT-PMP operations. It requires the Python extension module to be built. The wrapper allows for easy retrieval of the external IP address and configuration of discovery delays. ```python import libnatpmp # Create NAT-PMP client (auto-detects gateway) natpmp = libnatpmp.NATPMP() # Optional: set discovery delay in milliseconds natpmp.discoverdelay = 5000 # Get external/public IP address try: external_ip = natpmp.externalipaddress() print(f"Public IP: {external_ip}") except Exception as e: print(f"Failed to get public IP: {e}") ``` -------------------------------- ### Handle NAT-PMP Responses with Retry Logic Source: https://context7.com/miniupnp/libnatpmp/llms.txt Illustrates how to implement a robust response reader using readnatpmpresponseorretry. This function handles timeouts and retries automatically, ensuring the application waits for the gateway response correctly. ```c #include #include #include #include #include "natpmp.h" int wait_for_response(natpmp_t *natpmp, natpmpresp_t *response) { int r; struct timeval timeout; fd_set fds; int sav_errno; do { FD_ZERO(&fds); FD_SET(natpmp->s, &fds); r = getnatpmprequesttimeout(natpmp, &timeout); if (r < 0) return r; r = select(FD_SETSIZE, &fds, NULL, NULL, &timeout); if (r < 0) { perror("select() failed"); return -1; } r = readnatpmpresponseorretry(natpmp, response); sav_errno = errno; if (r < 0 && r != NATPMP_TRYAGAIN) { return r; } } while (r == NATPMP_TRYAGAIN); return r; } ``` -------------------------------- ### Detect Default Gateway (C) Source: https://context7.com/miniupnp/libnatpmp/llms.txt A low-level utility function to automatically detect the system's default gateway IP address. It employs platform-specific methods for compatibility across different operating systems like Linux, BSD, macOS, and Windows. ```c #include #include #include #include "getgateway.h" int main() { in_addr_t gateway; struct in_addr gateway_addr; int r; r = getdefaultgateway(&gateway); if (r == 0) { gateway_addr.s_addr = gateway; printf("Default gateway: %s\n", inet_ntoa(gateway_addr)); } else { fprintf(stderr, "Failed to detect default gateway\n"); } return r; } /* Expected output: * Default gateway: 192.168.1.1 */ ``` -------------------------------- ### Request Public IP Address (C) Source: https://context7.com/miniupnp/libnatpmp/llms.txt Sends a NAT-PMP request to retrieve the public IP address of the NAT gateway using libnatpmp. It involves sending the request, then asynchronously reading the response using select() and readnatpmpresponseorretry(). The function handles retries and returns the public IP address upon success. ```c #include #include #include #include #include "natpmp.h" int main() { natpmp_t natpmp; natpmpresp_t response; int r; struct timeval timeout; fd_set fds; initnatpmp(&natpmp, 0, 0); /* Send request for public IP address */ r = sendpublicaddressrequest(&natpmp); printf("sendpublicaddressrequest returned %d (%s)\n", r, r == 2 ? "SUCCESS" : "FAILED"); /* Wait for response with retry logic */ do { FD_ZERO(&fds); FD_SET(natpmp.s, &fds); getnatpmprequesttimeout(&natpmp, &timeout); select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(&natpmp, &response); } while (r == NATPMP_TRYAGAIN); if (r == 0 && response.type == NATPMP_RESPTYPE_PUBLICADDRESS) { printf("Public IP address: %s\n", inet_ntoa(response.pnu.publicaddress.addr)); printf("Epoch: %u seconds\n", response.epoch); } closenatpmp(&natpmp); return 0; } /* Expected output: * sendpublicaddressrequest returned 2 (SUCCESS) * Public IP address: 203.0.113.45 * Epoch: 123456 seconds */ ``` -------------------------------- ### sendnewportmappingrequest - Create or Delete Port Mapping Source: https://context7.com/miniupnp/libnatpmp/llms.txt This function creates a new port mapping on the NAT gateway or deletes an existing one. To delete a specific mapping, set the lifetime to 0. To delete all mappings for the host, set both ports and lifetime to 0. ```APIDOC ## sendnewportmappingrequest ### Description Creates a new port mapping on the NAT gateway, allowing external traffic to reach an internal port. Set lifetime to 0 to delete a mapping, or set both ports and lifetime to 0 to delete all mappings for the host. ### Method NATPMP (Implicit) ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **natpmp** (natpmp_t*) - Pointer to the natpmp context structure. - **protocol** (int) - Protocol for the mapping (NATPMP_PROTOCOL_TCP or NATPMP_PROTOCOL_UDP). - **private_port** (unsigned short) - The internal/private port number. - **public_port** (unsigned short) - The external/public port number (0 for any available). - **lifetime** (unsigned int) - The duration of the mapping in seconds (0 to delete). ### Request Example ```c #include #include #include #include #include "natpmp.h" int main() { natpmp_t natpmp; natpmpresp_t response; int r; struct timeval timeout; fd_set fds; initnatpmp(&natpmp, 0, 0); /* Create TCP port mapping: external 8080 -> internal 80, lifetime 3600s */ r = sendnewportmappingrequest(&natpmp, NATPMP_PROTOCOL_TCP, /* protocol: TCP(2) or UDP(1) */ 80, /* private/internal port */ 8080, /* public/external port (0 = any) */ 3600); /* lifetime in seconds */ printf("sendnewportmappingrequest returned %d (%s)\n", r, r == 12 ? "SUCCESS" : "FAILED"); /* Wait for response */ do { FD_ZERO(&fds); FD_SET(natpmp.s, &fds); getnatpmprequesttimeout(&natpmp, &timeout); select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(&natpmp, &response); } while (r == NATPMP_TRYAGAIN); if (r == 0) { printf("Mapped public port %u to local port %u\n", response.pnu.newportmapping.mappedpublicport, response.pnu.newportmapping.privateport); printf("Lifetime: %u seconds\n", response.pnu.newportmapping.lifetime); } /* Delete the mapping by setting lifetime to 0 */ sendnewportmappingrequest(&natpmp, NATPMP_PROTOCOL_TCP, 80, 8080, 0); do { FD_ZERO(&fds); FD_SET(natpmp.s, &fds); getnatpmprequesttimeout(&natpmp, &timeout); select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(&natpmp, &response); } while (r == NATPMP_TRYAGAIN); printf("Mapping deleted\n"); /* Delete ALL mappings for this host */ sendnewportmappingrequest(&natpmp, NATPMP_PROTOCOL_TCP, 0, 0, 0); closenatpmp(&natpmp); return 0; } ``` ### Response #### Success Response (0) - **response** (natpmpresp_t*) - Structure containing the response details. - **pnu.newportmapping.mappedpublicport** (unsigned short) - The public port that was mapped. - **pnu.newportmapping.privateport** (unsigned short) - The private port that was mapped. - **pnu.newportmapping.lifetime** (unsigned int) - The lifetime of the mapping in seconds. #### Response Example ```json { "mappedpublicport": 8080, "privateport": 80, "lifetime": 3600 } ``` #### Error Codes - **12**: SUCCESS - **NATPMP_TRYAGAIN**: Indicates that a response is not yet available and the operation should be retried. - Other negative values indicate specific errors (e.g., NATPMP_ERR_INVALIDARGS, NATPMP_ERR_NOPENDINGREQ). ### Expected output: ``` sendnewportmappingrequest returned 12 (SUCCESS) Mapped public port 8080 to local port 80 Lifetime: 3600 seconds Mapping deleted ``` ``` -------------------------------- ### readnatpmpresponseorretry - Read Response with Automatic Retry Source: https://context7.com/miniupnp/libnatpmp/llms.txt Reads the response from a pending NAT-PMP request. This function automatically handles retries with exponential backoff as specified in RFC 6886. It returns NATPMP_TRYAGAIN if no response is available yet, indicating that the caller should wait and try again. ```APIDOC ## readnatpmpresponseorretry ### Description Reads the response from a pending NAT-PMP request, automatically handling retries with exponential backoff as specified in RFC 6886. Returns NATPMP_TRYAGAIN if no response is available yet. ### Method NATPMP (Implicit) ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **natpmp** (natpmp_t*) - Pointer to the natpmp context structure. - **response** (natpmpresp_t*) - Pointer to a structure where the response will be stored. ### Request Example ```c #include #include #include #include #include "natpmp.h" int wait_for_response(natpmp_t *natpmp, natpmpresp_t *response) { int r; struct timeval timeout; fd_set fds; int sav_errno; do { FD_ZERO(&fds); FD_SET(natpmp->s, &fds); /* Get timeout for current retry attempt */ r = getnatpmprequesttimeout(natpmp, &timeout); if (r < 0) return r; /* Wait for socket to be readable or timeout */ r = select(FD_SETSIZE, &fds, NULL, NULL, &timeout); if (r < 0) { perror("select() failed"); return -1; } /* Try to read response */ r = readnatpmpresponseorretry(natpmp, response); sav_errno = errno; if (r < 0 && r != NATPMP_TRYAGAIN) { /* Real error occurred */ #ifdef ENABLE_STRNATPMPERR fprintf(stderr, "Error: %s\n", strnatpmperr(r)); #endif fprintf(stderr, "errno=%d '%s'\n", sav_errno, strerror(sav_errno)); return r; } /* NATPMP_TRYAGAIN (-100) means keep waiting */ } while (r == NATPMP_TRYAGAIN); return r; } ``` ### Response #### Success Response (0) - **response** (natpmpresp_t*) - Structure containing the response details. #### Response Example ```json { "status": 0, "details": "Success" } ``` #### Error Codes - **0**: Success, response filled. - **NATPMP_TRYAGAIN (-100)**: No response yet, call again. - **NATPMP_ERR_INVALIDARGS (-1)**: Invalid arguments provided. - **NATPMP_ERR_NOPENDINGREQ (-6)**: No pending request to respond to. - **NATPMP_ERR_NOGATEWAYSUPPORT (-7)**: Gateway does not support NAT-PMP. - **NATPMP_ERR_WRONGPACKETSOURCE (-9)**: Response received from an unexpected source. ``` -------------------------------- ### NAT-PMP Public Address Request API Source: https://context7.com/miniupnp/libnatpmp/llms.txt Sends a request to the NAT gateway to obtain the public IP address of the network. This is an asynchronous operation requiring subsequent calls to read the response. ```APIDOC ## sendpublicaddressrequest - Request External IP Address ### Description Sends a NAT-PMP request to retrieve the public/external IP address assigned to the NAT gateway. This is an asynchronous operation; use readnatpmpresponseorretry() to retrieve the response. ### Method C Function Call ### Endpoint N/A (Local Library Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c #include #include #include #include #include "natpmp.h" int main() { natpmp_t natpmp; natpmpresp_t response; int r; struct timeval timeout; fd_set fds; initnatpmp(&natpmp, 0, 0); /* Send request for public IP address */ r = sendpublicaddressrequest(&natpmp); printf("sendpublicaddressrequest returned %d (%s)\n", r, r == 2 ? "SUCCESS" : "FAILED"); /* Wait for response with retry logic */ do { FD_ZERO(&fds); FD_SET(natpmp.s, &fds); getnatpmprequesttimeout(&natpmp, &timeout); select(FD_SETSIZE, &fds, NULL, NULL, &timeout); r = readnatpmpresponseorretry(&natpmp, &response); } while (r == NATPMP_TRYAGAIN); if (r == 0 && response.type == NATPMP_RESPTYPE_PUBLICADDRESS) { printf("Public IP address: %s\n", inet_ntoa(response.pnu.publicaddress.addr)); printf("Epoch: %u seconds\n", response.epoch); } closenatpmp(&natpmp); return 0; } ``` ### Response #### Success Response (200) - **addr** (struct in_addr) - The public IP address. - **epoch** (unsigned int) - The epoch time in seconds. #### Response Example ``` sendpublicaddressrequest returned 2 (SUCCESS) Public IP address: 203.0.113.45 Epoch: 123456 seconds ``` ``` -------------------------------- ### Close NAT-PMP Session (C) Source: https://context7.com/miniupnp/libnatpmp/llms.txt Closes an active NAT-PMP session, releasing all associated resources including the UDP socket. The function returns 0 on success and specific error codes on failure, such as NATPMP_ERR_INVALIDARGS or NATPMP_ERR_CLOSEERR. ```c #include #include "natpmp.h" int main() { natpmp_t natpmp; int r; r = initnatpmp(&natpmp, 0, 0); if (r < 0) return 1; /* ... perform NAT-PMP operations ... */ r = closenatpmp(&natpmp); printf("closenatpmp() returned %d (%s)\n", r, r == 0 ? "SUCCESS" : "FAILED"); return r; } /* Return values: * 0 = SUCCESS * NATPMP_ERR_INVALIDARGS (-1) * NATPMP_ERR_CLOSEERR (-4) */ ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.