From 7717a97dd539ce7b89b6ed7856a1afb7d94e163f Mon Sep 17 00:00:00 2001
From: Piotr Grzybowski <merlin@narsil.org.pl>
Date: Wed, 23 Dec 2015 10:43:37 +0100
Subject: [PATCH] insert local port to LOCALPORT variable after successfull
 connection via network redirections.

---
 redir.c | 27 +++++++++++++++++++++++++++
 1 file changed, 27 insertions(+)

diff --git a/redir.c b/redir.c
index 0f40bd0..645e16f 100644
--- a/redir.c
+++ b/redir.c
@@ -36,6 +36,11 @@
 #  include <unistd.h>
 #endif
 
+#if defined(NETWORK_REDIRECTIONS) && defined(HAVE_NETWORK)
+#  include <sys/socket.h>
+#  include <netinet/in.h>
+#endif
+
 #include <errno.h>
 
 #if !defined (errno)
@@ -549,6 +554,12 @@ redir_special_open (spec, filename, flags, mode, ri)
 #if !defined (HAVE_DEV_FD)
   intmax_t lfd;
 #endif
+#if defined(NETWORK_REDIRECTIONS) && defined(HAVE_NETWORK)
+  struct sockaddr_storage address;
+  socklen_t address_length;
+  int rc;
+  char *port;
+#endif
 
   fd = -1;
   switch (spec)
@@ -582,6 +593,22 @@ redir_special_open (spec, filename, flags, mode, ri)
     case RF_DEVUDP:
 #if defined (HAVE_NETWORK)
       fd = netopen (filename);
+      if (fd != -1)
+        {
+          rc = getsockname (fd, (struct sockaddr *)&address, &address_length);
+          if (rc == 0 && address.ss_family == AF_INET)
+            {
+              port = itos (ntohs (((struct sockaddr_in *)&address)->sin_port));
+              bind_variable ("LOCALPORT", port, 0);
+              free (port);
+            }
+          if (rc == 0 && address.ss_family == AF_INET6)
+            {
+              port = itos (ntohs (((struct sockaddr_in6 *)&address)->sin6_port));
+              bind_variable ("LOCALPORT", port, 0);
+              free (port);
+            }
+        }
 #else
       internal_warning (_("/dev/(tcp|udp)/host/port not supported without networking"));
       fd = open (filename, flags, mode);
-- 
2.4.3

