Search code examples
javacsocketsdataoutputstream

write int from Java client to c server over socket


I thought it might be byte ordering but it doesn't look like it. I am not sure what else it could be.

Java client on linux

private static final int CODE = 0;
Socket socket = new Socket("10.10.10.10", 50505);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeInt(CODE);

c server also on linux

int sd = createSocket();
int code = -1;
int bytesRead = 0;
int result;

while (bytesRead < sizeof(int))
{
    result = read(sd, &code + bytesRead, sizeof(int) - bytesRead);
    bytesRead += result;
}

int ntolCode = ntohl(code); //test for byte order issue

printf("\n%i\n%i\n%i\n", code, ntolCode, bytesRead);

Which prints out:

-256
16777215
4

Not sure what else to try.

Solution

This solution is not intuitive in the least for me, but thanks for the down votes anyway!

Java side

Socket socket = new Socket("10.10.10.10", 50505);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
int x = 123456;
ByteBuffer buff = ByteBuffer.allocate(4);
byte[] b = buff.order(ByteOrder.LITTLE_ENDIAN).putInt(x).array();
out.write(b);

C side

int sd = createSocket();

char buff[4];
int bytesRead = 0;
int result;
while (bytesRead < 4){
    result = read(sd, buff + bytesRead, sizeof(buff) - bytesRead);
    if (result < 1) {
        return -1;
    }
    bytesRead += result;
}

int answer = (buff[3] << 24 | buff[2] << 16 | buff[1] << 8 | buff[0]);

I am still interested in a simpler solution if anyone has anything, preferably using BufferedWriter if that is possible.


Solution

  • The problem is here:

    &code + bytesRead
    

    This will increment the address of code in steps of 4 (sizeof code), not 1. You need a byte array, or some typecasting.