---
title: "How would I choose in java that which port is free to use for ServerSocket or Socket?"  
description: "How would I choose in java that which port is free to use for ServerSocket or Socket?"  
author: "Anonymous User"  
published: 2015-12-01  
updated: 2015-12-01  
canonical: https://www.mindstick.com/forum/33666/how-would-i-choose-in-java-that-which-port-is-free-to-use-for-serversocket-or-socket  
category: "java"  
tags: ["java"]  
reading_time: 1 minute  

---

# How would I choose in java that which port is free to use for ServerSocket or Socket?

I'm working on java. How would I [check](https://yourviews.mindstick.com/story/2248/never-forget-to-check-these-specifications-before-buying-a-mobile-phone) that a [port](https://www.mindstick.com/blog/11936/igor-mazepa-takes-part-in-another-corruption-operation-connected-with-odessa-port-plant) is [free](https://www.mindstick.com/articles/12963/3-free-things-to-do-in-valletta) to use for a ServerSocket? Moreover when a Socket is returned by the [accept](https://yourviews.mindstick.com/view/81278/we-have-to-accept-that-roger-federer-is-the-richest-one)() [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) is it given a port and [IP address](https://www.mindstick.com/articles/188405/difference-between-mac-address-and-ip-address) by [default](https://www.mindstick.com/interview/12771/what-is-the-importance-of-default-resources) or I would have to specify that too?

## Replies

### Reply by Anonymous User

You wouldn't need to check. You would specify port 0, which causes the system to give you a free port.Yes , It is given the IP address that the peer connected to, and the same port as the listening socket.No we won't need to specify the port and IP address.\
You can use the java.net.ServerSocket constructor with port 0 which tells ServerSocket to find a free port.Example :

```
int port = -1;try {    ServerSocket socket = new ServerSocket(0);    // here's your free port    port = socket.getLocalPort();    socket.close();} catch (IOException ioe) {}
```

\
\
Also, we can use 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
```


---

Original Source: https://www.mindstick.com/forum/33666/how-would-i-choose-in-java-that-which-port-is-free-to-use-for-serversocket-or-socket

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
