14

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)?

6
  • 4
    it's not going to change (ever) unless they redesign TCP to allow a higher port number (which isn't needed); 0xffff is a quick way to place it down Commented Aug 22, 2014 at 7:46
  • 2
    I would create a local constant in the class where you need it. Commented Aug 22, 2014 at 7:51
  • 3
    I think the question is relevant. Why would we have to define a well-known constant? Commented Aug 24, 2014 at 21:29
  • 1
    I just don't see why I have to define it myself as it is defined by an RFC (ietf.org/rfc/rfc793.txt), and it's regarding something as broadly used as TCP, so you'd expect it to be defined somewhere common and logical. I personally expected it in java's java.net.Socket, because that one uses ports of course and out of java's own classes, it's the class that's based on TCP the most. Commented Aug 25, 2014 at 5:47
  • 1
    You could use (Short.MAX_VALUE << 1) :) Commented Mar 3, 2015 at 13:25

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.