Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum tcp port number constant in java

Tags:

java

tcp

Is there a public constant for the maximum TCP port number (65535) defined in java or a common library such as Apache Commons, that I could refer to from my code (instead of using the integer hardcoded)?

like image 541
dammkewl Avatar asked Aug 22 '14 07:08

dammkewl


People also ask

What is the maximum port number that can be assigned?

Port numbers above 1023 can be either registered or dynamic (also called private or non-reserved). Registered ports are in the range 1024 to 49151. Dynamic ports are in the range 49152 to 65535. As mentioned, most new port assignments are in the range from 1024 to 49151.

Why are ports limited to 65535?

The port identifiers are unsigned 16-bit integers, meaning that the largest number you can put in there is 216-1 = 65535.

Can port 65535 be used?

Each port has a port number for identification. Port numbers 0 - 1023 are used for well-known ports. Port numbers 1024 - 65535 are available for the following user applications: Port numbers 1024 - 49151 are reserved for user server applications.

What is the valid range of port numbers?

Range of port values (PORT) Valid values range from 1 through 65535. However, some of the ports in the range 1 through 1023 are used by system-supplied TCP/IP applications. If the user specifies one of these ports, it can affect the operation of those applications.


1 Answers

I'm afraid there is none you can use.

Looking at the source code of Java 8 I see the following code used by the Socket class to verify a valid port in several functions:

private static int checkPort(int port) {
    if (port < 0 || port > 0xFFFF)
        throw new IllegalArgumentException("port out of range:" + port);
    return port;
}

This can be found in java.net.InetSocketAddress.checkPort(int)

As you can see Java itself doesn't use a named constant either.

A search of the code turns up the following hit in java.net.HostPortrange:

static final int PORT_MIN = 0;
static final int PORT_MAX = (1 << 16) -1;

But as you can see this isn't a public reference. Another private reference turns up in java.net.SocketPermission.

So after the inspection above, I conclude there is none available in the Java API.

like image 178
Thirler Avatar answered Sep 23 '22 01:09

Thirler