Amir Zadeh
Amir Zadeh

Reputation: 3629

Getting an open socket for tcp connection in java

I'm developing a torrent with Java and there is a small question I have. How can I get an open socket for my process in java? I need about 100 free sockets in a sequence, just like 10000-10100. All I know is that by using

socket = new Socket(ip, port);

We need to provide ip and port. Well of course this is the case of debug and my ip is loopback, but I could find only one free port by using random numbers in port field. Please tell me how to find a sequence of free ports for tcp.

Upvotes: 1

Views: 3304

Answers (3)

alpian
alpian

Reputation: 4748

You can't guarantee free port numbers. You will have to scan the ports on the machine looking for free ports anywhere between 1024 and 65535. If you want to create a client socket you would have to try and connect from each local port you want in sequence, aborting and starting again if you encounter a used port - but of course this could keep happening if another application is trying to grab ports too. For a server socket, you would have to try and bind to each port in sequence.

For a client socket, do you need to specify the local port? If not, just allocate the number of connections you want. For a server socket, I would simply assume that I owned all ports from, say 10000 to 10100. Although starting a hundred servers probably isn't what you want to do.

With any networking in Java, rather than using the Java .net package, rather use Netty which is much easier to work with.

Upvotes: 1

user207421
user207421

Reputation: 310903

Why do you need a range of port numbers at the client? You can get a free listening port via new ServerSocket(0) and interrogating the local port. But there's no good reason why you should need a range of client port numbers (other than over-enthusiastic outbound firewall rules, which netadmins sometimes specify without realizing there is no API to use them).

Upvotes: 0

Qwerky
Qwerky

Reputation: 18435

This might shed some light;

http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

Upvotes: 1

Related Questions