Skip to content

Commit

Permalink
Reuse NAT port forwarding if possible
Browse files Browse the repository at this point in the history
  • Loading branch information
BeatWolf committed Jul 2, 2018
1 parent 55393ae commit 7702c6a
Showing 1 changed file with 13 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,13 @@ public Tuple<String, Integer> call() throws Exception {
LogWriter.writeDebugInfo("Port " + port + " is already forwarded to ourself");
}else {
LogWriter.writeDebugInfo("Port " + port + " is already forwarded to "+portMapping.getInternalClient());
newPort = getFreeNATPort(port);
LogWriter.writeDebugInfo("Remap " + port + " to "+newPort);
newPort = getFreeNATPort(localAddress, port);
if(newPort < 0) {
LogWriter.writeDebugInfo("Remap of " + port + " to "+newPort+" is already in place");
directMapping = true;
}else {
LogWriter.writeDebugInfo("Remap " + port + " to "+newPort);
}
}
}

Expand Down Expand Up @@ -183,7 +188,7 @@ public void run() {
}
}

private static int getFreeNATPort(int port) throws IOException, SAXException {
private static int getFreeNATPort(InetAddress localAddress, int port) throws IOException, SAXException {

int counter = 0;
do {
Expand All @@ -193,9 +198,13 @@ private static int getFreeNATPort(int port) throws IOException, SAXException {
return port;
}

if(portMapping.getInternalClient().equals(localAddress.getHostAddress())) {
return -port;
}

//Abort after 1000 ports
if(counter++ > 1000) {
return -1;
return 0;
}
}while(true);

Expand Down

0 comments on commit 7702c6a

Please sign in to comment.