From bbb27ab97d1a0d56429701f32e1c720f3ec940ff Mon Sep 17 00:00:00 2001 From: Thomas Bernard Date: Fri, 26 May 2017 12:08:03 +0200 Subject: [PATCH] miniupnpc-async: retrieve our ip address --- miniupnpc-async/miniupnpc-async.c | 7 +++++++ miniupnpc-async/miniupnpc-async.h | 5 +++++ miniupnpc-async/testasync.c | 12 +++++++++++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/miniupnpc-async/miniupnpc-async.c b/miniupnpc-async/miniupnpc-async.c index 0ef3559..602ee18 100644 --- a/miniupnpc-async/miniupnpc-async.c +++ b/miniupnpc-async/miniupnpc-async.c @@ -402,6 +402,13 @@ static int upnpc_send_request(upnpc_device_t * p) "Connection: Close\r\n" "User-Agent: MiniUPnPc-async\r\n" "\r\n"; + + /* retrieve "our" IP address used to connect to the UPnP device */ + p->selfaddrlen = sizeof(struct sockaddr_storage); + if(getsockname(p->http_socket, (struct sockaddr *)&p->selfaddr, &p->selfaddrlen) < 0) { + PRINT_SOCKET_ERROR("getsockname()"); + } + if(p->http_request == NULL) { char hostname[MAXHOSTNAMELEN+1]; unsigned short port; diff --git a/miniupnpc-async/miniupnpc-async.h b/miniupnpc-async/miniupnpc-async.h index d4eff71..91f5378 100644 --- a/miniupnpc-async/miniupnpc-async.h +++ b/miniupnpc-async/miniupnpc-async.h @@ -17,6 +17,9 @@ #ifndef MINIUPNPC_ASYNC_H_INCLUDED #define MINIUPNPC_ASYNC_H_INCLUDED +/* for struct sockaddr_storage */ +#include + #include "declspec.h" #include "upnpreplyparse.h" @@ -64,6 +67,8 @@ typedef struct upnpc_device { int http_response_chunked; int http_response_code; struct NameValueParserData soap_response_data; + struct sockaddr_storage selfaddr; + socklen_t selfaddrlen; } upnpc_device_t; typedef struct { diff --git a/miniupnpc-async/testasync.c b/miniupnpc-async/testasync.c index 9a970e3..b940618 100644 --- a/miniupnpc-async/testasync.c +++ b/miniupnpc-async/testasync.c @@ -17,6 +17,10 @@ #include #include #include +/* for getnameinfo() : */ +#include +#include +#include /* compile with -DUPNPC_USE_SELECT to enable upnpc_select_fds() function */ #include "miniupnpc-async.h" #include "upnpreplyparse.h" @@ -30,6 +34,7 @@ enum methods { int main(int argc, char * * argv) { + char ip_address[64]; int r, n; upnpc_t upnp; const char * multicastif = NULL; @@ -120,10 +125,15 @@ int main(int argc, char * * argv) next_method_to_call = EAddPortMapping; break; case EAddPortMapping: + if(getnameinfo((struct sockaddr *)&upnp.device_list->selfaddr, upnp.device_list->selfaddrlen, + ip_address, sizeof(ip_address), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV) < 0) { + fprintf(stderr, "getnameinfo() failed\n"); + } + printf("our IP address is %s\n", ip_address); printf("AddPortMapping\n"); upnpc_add_port_mapping(upnp.device_list, /* XXX */ NULL /* remote_host */, 40002 /* ext_port */, - 42042 /* int_port */, "192.168.1.202" /* int_client */, + 42042 /* int_port */, ip_address /* int_client */, "TCP" /* proto */, "this is a test" /* description */, 0 /* lease duration */); next_method_to_call = ENothing;