On Localhost, How to Pick a Free Port Number

On localhost, how do I pick a free port number?

Do not bind to a specific port. Instead, bind to port 0:

import socket
sock = socket.socket()
sock.bind(('', 0))
sock.getsockname()[1]

The OS will then pick an available port for you. You can get the port that was chosen using sock.getsockname()[1], and pass it on to the slaves so that they can connect back.

sock is the socket that you created, returned by socket.socket.

How to pick a free port number in python?

There likely is not a safe way to do what you're asking. Even if the OS could return a port to you that is currently free, there's no guarantee that another process wouldn't bind a socket to that port between the time where you request the port and when the application you invoke attempts to bind to it.

Given that, if you're just looking for a port that is likely free, you could bind to port 0 as described here On localhost, how to pick a free port number?, close the resulting socket (freeing the port), and then pass that value to your application.

How to find an available port?

If you don't mind the port used, specify a port of 0 to the ServerSocket constructor and it will listen on any free port.

ServerSocket s = new ServerSocket(0);
System.out.println("listening on port: " + s.getLocalPort());

If you want to use a specific set of ports, then the easiest way is probably to iterate through them until one works. Something like this:

public ServerSocket create(int[] ports) throws IOException {
for (int port : ports) {
try {
return new ServerSocket(port);
} catch (IOException ex) {
continue; // try next port
}
}

// if the program gets here, no port in the range was found
throw new IOException("no free port found");
}

Could be used like so:

try {
ServerSocket s = create(new int[] { 3843, 4584, 4843 });
System.out.println("listening on port: " + s.getLocalPort());
} catch (IOException ex) {
System.err.println("no available ports");
}

How to find a free local port using Swift?

Here's a working solution:

func findFreePort() -> UInt16 {
var port: UInt16 = 8000;

let socketFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if socketFD == -1 {
//print("Error creating socket: \(errno)")
return port;
}

var hints = addrinfo(
ai_flags: AI_PASSIVE,
ai_family: AF_INET,
ai_socktype: SOCK_STREAM,
ai_protocol: 0,
ai_addrlen: 0,
ai_canonname: nil,
ai_addr: nil,
ai_next: nil
);

var addressInfo: UnsafeMutablePointer<addrinfo>? = nil;
var result = getaddrinfo(nil, "0", &hints, &addressInfo);
if result != 0 {
//print("Error getting address info: \(errno)")
close(socketFD);

return port;
}

result = Darwin.bind(socketFD, addressInfo!.pointee.ai_addr, socklen_t(addressInfo!.pointee.ai_addrlen));
if result == -1 {
//print("Error binding socket to an address: \(errno)")
close(socketFD);

return port;
}

result = Darwin.listen(socketFD, 1);
if result == -1 {
//print("Error setting socket to listen: \(errno)")
close(socketFD);

return port;
}

var addr_in = sockaddr_in();
addr_in.sin_len = UInt8(MemoryLayout.size(ofValue: addr_in));
addr_in.sin_family = sa_family_t(AF_INET);

var len = socklen_t(addr_in.sin_len);
result = withUnsafeMutablePointer(to: &addr_in, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
return Darwin.getsockname(socketFD, $0, &len);
}
});

if result == 0 {
port = addr_in.sin_port;
}

Darwin.shutdown(socketFD, SHUT_RDWR);
close(socketFD);

return port;
}

How would I choose in java that which port is free to use for ServerSocket or Socket?

Use Try catch to find a free port

private static int port=9000;
public static int detectPort(int prt)
{
try{
//connect to port
}
catch(Exception e)
{
return detectPort(prt+1);
}
return prt;
}

// Write detectPort(port); inside main

Nodejs random free tcp ports

You can bind to a random, free port assigned by the OS by specifying 0 for the port. This way you are not subject to race conditions (e.g. checking for an open port and some process binding to it before you get a chance to bind to it).

Then you can get the assigned port by calling server.address().port.

Example:

var net = require('net');

var srv = net.createServer(function(sock) {
sock.end('Hello world\n');
});
srv.listen(0, function() {
console.log('Listening on port ' + srv.address().port);
});

With Twisted python is there a mechanism to find a free port similar to socket.open?

Like so:

reactor.listenTCP(0, ...)


Related Topics



Leave a reply



Submit