Skip to content

Commit

Permalink
fix(port): updated code for port verification To
Browse files Browse the repository at this point in the history
Improved the code for the port checking and introduced retries and waiting time
  • Loading branch information
alirana01 committed Sep 13, 2024
1 parent bf7792c commit 5d4bfad
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*******************************************************************************/
package com.espressif.idf.core.util;

import java.io.IOException;
import java.net.Socket;

import com.espressif.idf.core.logging.Logger;
Expand All @@ -24,14 +25,45 @@ private PortChecker()

public static boolean isPortAvailable(int port)
{
try (Socket ignored = new Socket("localhost", port)) //$NON-NLS-1$
{
return false;
}
catch (Exception e)
int attempts = 0;
int retryCount = 3;
long retryDelayMillis = 200;

while (attempts <= retryCount)
{
return true;
try (Socket ignored = new Socket("localhost", port)) //$NON-NLS-1$
{
// If the socket opens, the port is in use
return false;
}
catch (IOException e)
{
// Port is unavailable, retrying if there are attempts left
if (attempts == retryCount)
{
// After exhausting all retries, return false
Logger.log("Port " + port + " is not available after " + retryCount + " retries."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return false; // Failure, port is still not available
}

attempts++;

// Log retry attempt
Logger.log("Attempt " + attempts + " failed, retrying in " + retryDelayMillis + " ms..."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

try
{
Thread.sleep(retryDelayMillis);
}
catch (InterruptedException interruptedException)
{
Thread.currentThread().interrupt(); // Restore interrupt status
Logger.log("Port availability check interrupted."); //$NON-NLS-1$
return false; // If interrupted, assume port unavailable and stop
}
}
}
return true; //Fallback not reachable
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,12 @@ protected void provideDefaults(ILaunchConfigurationWorkingCopy config) throws Co
fDefaultPreferences.getGdbClientExecutable());
}

int availableRemotePort = PortChecker.getAvailablePort(config.getAttribute(IGDBJtagConstants.ATTR_PORT_NUMBER,
DefaultPreferences.GDB_SERVER_GDB_PORT_NUMBER_DEFAULT));
config.setAttribute(IGDBJtagConstants.ATTR_PORT_NUMBER, availableRemotePort);
if (Configuration.getDoStartGdbServer(config))
{
int availableRemotePort = PortChecker.getAvailablePort(config.getAttribute(IGDBJtagConstants.ATTR_PORT_NUMBER,
DefaultPreferences.GDB_SERVER_GDB_PORT_NUMBER_DEFAULT));
config.setAttribute(IGDBJtagConstants.ATTR_PORT_NUMBER, availableRemotePort);
}

config.setAttribute(DebugPlugin.ATTR_PROCESS_FACTORY_ID, CustomIdfProcessFactory.ID);
}
Expand Down

0 comments on commit 5d4bfad

Please sign in to comment.