Nicolas Nicolas - 5 months ago 22
Java Question

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.

EJP EJP
Answer

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.

Comments