c ++ server htons to java ntohs client conversion

时间:2009-11-26 00:53:15

标签: java c++ data-conversion htonl

我正在创建一个小型TFTP客户端  开发服务器的服务器应用程序  使用c ++和客户端使用java。

这里我发送“块计数”值  使用htons转化。

但我无法将其转换回来  在客户端的原始价值。

例如,如果发送块计数  从服务器到ntohs(01)(2个字节)  客户。客户端以字节为单位读取。  我收到的值是字节0  和字节1。

如果有人可以提供  溶液

3 个答案:

答案 0 :(得分:3)

我认为你的意思是你使用ntohs 解码从网络读取的值,htons 编码发送的值通过网络。

ByteBuffer#getShort()一起调查ByteBuffer#order(ByteOrder)网络字节顺序 big endian ,因此请使用值ByteOrder#BIG_ENDIAN正确配置ByteBuffer。请注意,BIG_ENDIAN是默认顺序,但在这种情况下,明确说明您的偏好是一种很好的形式。


您没有提到您在Java中使用的网络通信内容。如果是java.net.Socket,您可以致电Socket#getChannel()获取java.nio.channels.SocketChanneljava.nio.channels.ByteChannel的子类型,您可以使用ByteBuffer来读取和写入数据

答案 1 :(得分:1)

   private void somemethod(){

    byte[] fileDataFull = new byte[516];
    byte[] receivedCounter = new byte[2];

    readLength = in.read(fileDataFull);

    receivedCounter[0] = fileDataFull[2];
    receivedCounter[1] = fileDataFull[3];

   if (expectedPktCount == convertntohs(receivedCounter)){

   }

   byte[] b = converthtons((short) expectedPktCount);

}

    private short convertntohs(byte[] value) {
        ByteBuffer buf = ByteBuffer.wrap(value);
        return buf.getShort();
    }

    private byte[] converthtons(short sValue) {
        byte[] baValue = new byte[2];
        ByteBuffer buf = ByteBuffer.wrap(baValue);
        return buf.putShort(sValue).array();
    }

答案 2 :(得分:0)

内部的Java数字始终按网络字节顺序排列,即使在本机整数/双精度数不存在的系统上也是如此。这意味着您可以将任何进入Java的数字转换为执行此类转换的任何基本输入流 - 实现java.io.DataInput。如果您使用的是java.nio.Channel,ByteBuffer也可以工作,但您可以更改字节顺序(ByteBuffer.order()),尽管默认情况下网络字节排序和Java内部存储是正确的。

顺便说一句,我认为您的意思是使用htons,但在示例中您显示的是ntohs。从C ++发送您要将 h ost order转换为 n etwork order。从Java(或任何客户端)接收服务器将使用ntohs转换回来。

相关问题