Writing Data Streams from C

Problem

You need to exchange binary data between C and Java.

Solution

Use the network byte-ordering macros.

Discussion

The program that created the file random.dat read by the program in the previous recipe was not written in Java, but in C. Since the earliest days of the TCP/IP protocol in the 1980s, and particularly on the 4.2 BSD version of Unix, there was an awareness that not all brands of computers store the bytes within a word in the same order, and there was a means for dealing with it. For this early heterogeneous network to function at all, it was necessary that a 32-bit word be interpreted correctly as a computer’s network address, regardless of whether it originated on a PDP-11, a VAX, a Sun workstation, or any other kind of machine then prevalent (there were no “IBM PC” machines powerful enough to run TCP/IP at that time). So network byte order was established, a standard for which bytes go in which order on the network. And the network byte order macros were written: ntohl for network-to-host order for a long (32 bits), htons for host-to-network order for a short (16 bits), and so on. In most Unix implementations, these C macros live in one of the Internet header files, although in some newer systems they have been segregated out into a file like <machine/endian.h>, as on our OpenBSD system.

The designers of Java, working at Sun, were well aware of these issues, and chose to use network byte order in the Java Virtual Machine. Thus a ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.