如何用Java表示TCP端口范围(16位)[重复]

时间:2022-04-11 18:36:02

This question already has an answer here:

这个问题在这里已有答案:

A port range goes from 0 to 65536 as it is stored as a 16-bit unsigned integer.

端口范围从0到65536,因为它存储为16位无符号整数。

In Java, a short which is 16-bit only goes up to 32,767. An integer would be fine, but the API expects an unsigned integer, so it must fit within 16 bits.

在Java中,只有16位的short才能达到32,767。一个整数可以,但API需要一个无符号整数,所以它必须适合16位。

My first attempt was as follows:

我的第一次尝试如下:

public byte[] encode() {
    final int MESSAGE_SIZE = 10;
    Bytebuffer buffer = ByteBuffer.allocate(MESSAGE_SIZE);
    buffer.putInt(someInt);
    buffer.putShort(portValue);
    buffer.putInt(someOtherInt); 
    return buffer.array();
}

But clearly, I cannot represent a port above 32,767 if I simply use a short.

但显然,如果我只是使用短线,我不能代表32,767以上的港口。

My question is, how can I put a value that can be up to 65536 as a short into the buffer so that the receiving API can interpret it within 16 bits?

我的问题是,如何将一个最多可达65536的值作为短路放入缓冲区,以便接收API能够在16位内解释它?

Thank you!

谢谢!

1 个解决方案

#1


2  

You just use a normal int in your program to store the port. When you want to send the int on the wire as a 16-bit value you simply cast it to a short. This just discards the high-order 16-bits (which you weren't using anyway) and the low-order 16-bits are are left unchanged. Example:

您只需在程序中使用普通的int来存储端口。如果要将线路上的int作为16位值发送,只需将其转换为short。这只是丢弃了高阶16位(你还没有使用),而低阶16位保持不变。例:

public byte[] encode() {
    final int MESSAGE_SIZE = 10;
    int portValue = 54321;
    Bytebuffer buffer = ByteBuffer.allocate(MESSAGE_SIZE);
    buffer.putInt(someInt);
    buffer.putShort((short) portValue);
    buffer.putInt(someOtherInt); 
    return buffer.array();
}

From Narrowing Primitive Conversions:

从缩小原始转换:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.

将有符号整数缩小到整数类型T只会丢弃除n个最低位之外的所有位,其中n是用于表示类型T的位数。

#1


2  

You just use a normal int in your program to store the port. When you want to send the int on the wire as a 16-bit value you simply cast it to a short. This just discards the high-order 16-bits (which you weren't using anyway) and the low-order 16-bits are are left unchanged. Example:

您只需在程序中使用普通的int来存储端口。如果要将线路上的int作为16位值发送,只需将其转换为short。这只是丢弃了高阶16位(你还没有使用),而低阶16位保持不变。例:

public byte[] encode() {
    final int MESSAGE_SIZE = 10;
    int portValue = 54321;
    Bytebuffer buffer = ByteBuffer.allocate(MESSAGE_SIZE);
    buffer.putInt(someInt);
    buffer.putShort((short) portValue);
    buffer.putInt(someOtherInt); 
    return buffer.array();
}

From Narrowing Primitive Conversions:

从缩小原始转换:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.

将有符号整数缩小到整数类型T只会丢弃除n个最低位之外的所有位,其中n是用于表示类型T的位数。