Nicolas Nicolas - 1 year ago 153
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("", 50505);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());

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:


Not sure what else to try.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download