java - 如何在 Java 中表示 TCP 端口范围(16 位)

标签 java c tcp junit

<分区>

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

在 Java 中,16 位的 short 最多只能达到 32,767。一个整数就可以了,但 API 需要一个无符号整数,因此它必须在 16 位以内。

我的第一次尝试如下:

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();
}

但很明显,如果我只是使用一个 short,我不能代表 32,767 以上的端口。

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

谢谢!

最佳答案

您只需在程序中使用普通的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();
}

来自 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.

关于java - 如何在 Java 中表示 TCP 端口范围(16 位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34998080/

相关文章:

java - 为什么maven在settings.xml中未配置的目录中使用本地存储库

java - Spring 启动: How to get running port of application deployed on JBoss (or any app server)?

Java传递任何类的对象作为参数

java - 如何从 XPages (java) 中的 POST 检索参数

c++ - 编译 Audacity MSB4023 项目元数据时出错,无法应用于 MSVC 2010

c# - 是什么导致了 MSSQL 中的错误 "Operation on non-blocking socket would block"?

c# - 从 C 转换为 C#,还是制作 DLL?

c - 如何创建 const 结构数组

c++ - Asio 中新连接出现 "Already Open"错误

java - 由于将请求从老板线程传递到工作线程而导致的 netty 延迟?