def next_free_port(port = 1024, max_port = 65535):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while port <= max_port:
try:
sock.bind(('', port))
sock.close()
return port
except OSError:
port += 1
raise IOError('no free ports')
Last Updated : 27 Jul, 2020
To use socket module ,we have to import it :
import socket
To create a new object of socket socket() is used. The syntax of socket() function is:
newSocket = socket.socket(socket_family, socket_type)
socket_family is ip address of version 4 or 6.By default it takes as IPV4.
AF_INET
for socket family of address version 4
AF_INET6
for socket family of address version 6
To Return a string containing the hostname of the machine where the Python interpreter is currently executing. we can use :
socket.gethostname()
If hostname is in IPV6 Following method is used Translate a host name to IPv4 address format. The IPv4 address is returned as a string, such as ‘10.120.30.2’. If the host name is an IPv4 address itself it is returned unchanged.
socket.gethostbyname(hostname)
Last modified: July 8, 2021
try (ServerSocket serverSocket = new ServerSocket(FREE_PORT_NUMBER)) {
assertThat(serverSocket).isNotNull();
assertThat(serverSocket.getLocalPort()).isEqualTo(FREE_PORT_NUMBER);
} catch (IOException e) {
fail("Port is not available");
}
In case we use a specific port twice, or it's already occupied by another application, the ServerSocket constructor will throw an IOException:
try (ServerSocket serverSocket = new ServerSocket(FREE_PORT_NUMBER)) {
new ServerSocket(FREE_PORT_NUMBER);
fail("Same port cannot be used twice");
} catch (IOException e) {
assertThat(e).hasMessageContaining("Address already in use");
}
Let's now check how we can make use of the thrown IOException, to create a server socket using the first free port from a given range of port numbers:
for (int port: FREE_PORT_RANGE) {
try (ServerSocket serverSocket = new ServerSocket(port)) {
assertThat(serverSocket).isNotNull();
assertThat(serverSocket.getLocalPort()).isEqualTo(port);
return;
} catch (IOException e) {
assertThat(e).hasMessageContaining("Address already in use");
}
}
fail("No free port in the range found");
int port = SocketUtils.findAvailableTcpPort();
try (ServerSocket serverSocket = new ServerSocket(port)) {
assertThat(serverSocket).isNotNull();
assertThat(serverSocket.getLocalPort()).isEqualTo(port);
} catch (IOException e) {
fail("Port is not available");
}
Jetty is a very popular embedded server for Java applications. It will automatically allocate a free port for us unless we set it explicitly via the setPort method of the ServerConnector class:
Server jettyServer = new Server();
ServerConnector serverConnector = new ServerConnector(jettyServer);
jettyServer.addConnector(serverConnector);
try {
jettyServer.start();
assertThat(serverConnector.getLocalPort()).isGreaterThan(0);
} catch (Exception e) {
fail("Failed to start Jetty server");
} finally {
jettyServer.stop();
jettyServer.destroy();
}