views:

57

answers:

3

In one side I have a Java client writing ints into its outputstream: int a = 20; dataout.writeInt(a); dataout.flush();

From the other side I have a C server listening the connection:

int client = accept(...);

How to read the int sent by Java?

If I had a Java server, i could easily write: int a = dataIn.readInt();

How to do this in C?

thanks

+1  A: 

Read it into a char buffer and use atoi() to convert the string into a int.

Timo Geusch
assuming an integer as 4 bytes, is this what you mean?char buf[4];read(client, buf, 4);int integer = atoi(buf);
Eduardo Abreu
Not quite - if the Java server is sending the Int as four bytes, the whole thing is going to get a lot more complicated as you basically need to know exactly in what byte order the Int is sent. I would try to send Int as a string, use a somewhat bigger buffer (16 bytes up) to store the string in and then use atoi as you suggested. If you're sending the Int as a byte representation, I would convert it to network byte order before sending and convert it back to host order once you received it, otherwise you're in a world of really odd bugs.
Timo Geusch
atoi has no error-handling, atoi("0") == atoi("blah"); better you use strtol
A: 

You can use the read function, but you have to be careful to consume sizeof(int) chars from the socket and then you have to worry about endianess.

Michael Goldshteyn
A: 

fscanf should work if you don't mind sending in plain text:

fscanf(dataIn, "%d", &a);

Plain text rules :-) Just be sure to send a '\n' (or something not a digit) from the source before the flush.

pmg