The server is coded in C and client is coded in Java. I have a struct in C with a few primitive data-types like int,char.The message structure is sent via socket. Say,i sent an int value of 4 from the C-side.
I use a DataInputStream on the Java-end and read the contents of the message into a byte.When i try to read the 1st 4 bytes,which denote an int,i get a huge value. I also tried DataInputStream.readInt(),but it gives the same value.
Now,I need to retrieve the same int value,that was sent from the C-side.
Originally posted by Stan James: I don't know C so I'm guessing at how to diagnose this.
* Is the size the same? 4-bytes on both sides? * Is the order the same? See this Endian Essay for what I mean.
In any case, I'd read one byte / char at a time and display them to see what's going on. Let us know what you find!
Hi stan,Thanks for the response.
am able to receive them in a byte array. and yeah,sizeof int in both C and Java is 4.
I don't know if this is the right place to post my query,but this problem was encountered, during the socket commn. between C and Java
I created a structure,struct1 on C-end with contents as int,char,char,int. Now,i Have another structure,struct2 with the reference of struct1 in it. The actual size of struct1 is 38,but when i say sizeof(struct1) or sizeof(struct2),it gives me 40. Extra zero values are padded after the 2nd char and thereby,I face problems in reading the 2nd int value.
The actual size of struct1 is 38,but when i say sizeof(struct1) or sizeof(struct2),it gives me 40.
The declared size of struct1 is 38 bits. The actual size of struct1 in memory is 40. C isn't a kind language like Java that hides the ugly details of memory management from you. It is a hard language where you are expected to know and deal with the nitty gritty details of memory. The smallest addressable piece of memory in an operating system is called a "word". You can declare a smaller piece, like a byte or a short, but you get a full word. When you declare a structure that does not end on a word boundary, it gets padded so that it does. A word in most modern operating systems is 32 bits, so your structure is getting padded to be 10 words. Read the two byte padding, throw them away and continue with your processing.
1. I presume you're coding using sockets on the 'C' language host.
If so, please be sure to use the "hton" and "htons" functions to convert from host to network byte order before you transmit. And the corresponding "ntoh" and "ntohs" functions to read int's and short's (respectively) back.
Java has no such functions because Java sockets send and receive ints, shorts (and, for that matter, longs) in network order automatically.
2. Consider downloading and familiarizing yourself with "Ethereal", to capture and analyze network traces. Ethereal can be an invaluable tool for debugging networked applications like yours.