Java Reference
In-Depth Information
Writing Data Streams from C
Problem
You need to exchange binary data between C and Java.
Solution
In your C code, use the network byte-ordering macros.
Discussion
The file
random.dat
read by the program in the previous recipe was not written by a Java
program, but by a C program. Java is certainly capable of writing it, but I wanted to show
that we can read binary data that was written in a language other than Java.
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 computer processors (CPUs) store the
bytes within a word in the same order, and developers of the day came up with a means for
dealing with it. The “big-endian” machines store the high-order bytes first, and “little-endi-
eous 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. So “network byte order” was
established, a standard for which bytes go in which order on the network. Network order is
big-endian, whereas the Intel/AMD x86 architecture is little-endian.
For C programmers, 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, al-
though in some newer systems, they have been segregated out into a file like
<machine/endi-
an.h>
, as on our OpenBSD system.
The designers of Java, working at Sun, were well aware of these issues and chose to use net-
work byte order in the Java Virtual Machine. Thus, a Java program can read an IP address
from a socket using a
DataInputStream
or write an integer to disk that will be read from C
using
read()
and the network byte order macros.