JDK5.0 Document: Networking IPv6 User Guide for JDK / JRE 5.0
This Document Covers The Following Topics:
Overview supported Operating Systems Using IPv6 in Java Details ON IPv6 Support in Java
Special IPv6 Address Types IPv6-Related System Properties Dual-Stack Node Java Application Impact IPv6 Networking Properties
Overview
Within the past few years IPv6 has gained much greater acceptance in the industry, especially in certain regions of the world, ie, Europe and the Asian Pacific. Extensibility, mobility, quality of service, larger address space, auto-configuration, security, multi - Homing, Anycast and Multicast, And Renumbering-these Area's made it it desirable.
With the release of J2SE 1.4 in February 2002, Java began supporting IPv6 on Solaris and Linux. Support for IPv6 on Windows was added with J2SE 1.5. While other languages, such as C and C can support IPv6, there are some major advantages to Java :
WITH JAVA You Invest In A Single Code Base That IS Both IPv4- and IPv6-Ready. Your Existing Java Applications Area ALREADY IPv6-Enabled. Migration To IPv6 IS Easy
We will ,,,,,,,,,,,.
Personal view: Through some porting work, I believe that Java does have its own advantages in IPv6 support and transplantation. Because it is an object-oriented language, address type inetaddress is easily derived from INET6ADDRESS and INET4ADDRESS, which can be said on the code. Very small, especially for C language. Just as mentioned in the JDK help documentation, Java network code is very simple to transition to IPv6. The code itself can easily transition to V4 / V6 pair support, which is really a lot of luck for Java programmers.
Supported Operating Systems
The Following Operating Systems Are Now Supported by the J2se Reference Implementation:
Solaris 8 and higher linux kernel 2.1.2 and higher (kernel 2.4.0 and higher recommended for better ipv6 support) Windows XP SP1 and Windows 2003 Perspective: JDK1.4.2 No problem with IPv6 in Solaris and Linux, but in The support of Java on IPv6 in the Windows environment is limited, possibly this and the Windows version itself is related to the limitations of IPv6 support. I remember that I used JDK1.4.2 under WindowXP to write IPv6's network programs, but the serverSocket is bound to report the error - the protocol type is not supported.
Currently, Windows2000 / XP / 2003 provides basic support for IPv6, and JDK1.5's support for IPv6 in the Windows environment is based.
Using IPv6 in Java
Using IPv6 in Java Is Easy; IT IS Transparent and Automatic. Unlike In Many Other. In Fact, There is no need to even recompile the source files. ~ It is indeed exciting, a lot of work in JDK During it, the change in the upper layer is more simple!
Consider an Example from the Java Tutorial:
Socket echosocket = null; printwriter out = null; bufferedreader in = null;
try {echoSocket = new Socket ( "taranis", 7); out = new PrintWriter (echoSocket.getOutputStream (), true); in = new BufferedReader (new InputStreamReader (echoSocket.getInputStream ()));} catch (UnknownHostException e) {System.err.Println ("Don't Know About Host: Taranis."); System.exit (1);} catch (ioException e) {system.err.println ("COULDN't Get I / O for" "The connection to: taranis."); System.exit (1);} // ... code omitted here CommunicatewithechoServer (OUT, IN);
Out.close (); in. close (); stdin.close (); echosocket.close ();
You Can Run The Same Bytecode for this Example In IPv6 Mode IF Both Your local host machine and the destination machine (taranis) Are IPv6-enabled.
From the perspective of the client, if the address resolution is the way through the host name or domain name, the client's code can hardly change.
In contrast, if you wanded the corresponding c Program To Run IN IPV6 MODE, You Would First Need to port it. Here's What Would Need to happen: The following cases are very common during the transplantation of V4 to V6, the workload is indeed Not small, but also to see the code of the address in the code, the transcoding process is very painful for the binding address structure of the full code, and the transplantation process is very painful!
Excerpt of Original C C code:
Struct SockAddr_in sin; struct hostent * hp; int sock;
/ * Open socket. * / Sock = socket (AF_INET, SOCK_STREAM, 0); if (SOCK == -1) {Perror ("socket"); return (-1);} / * get host address * / hp = GethostByname; if (hp == null || hp-> h_addrtype! = af_inet || hp-> h_length! = 4) {(void) FPrintf (stderr, "unknown host '% s' / n", hostname ); (Void); Return (-1);}
Sin.sin_Family = AF_INET; SIN.SIN_PORT = HTONS (port); (void) Memcpy (void *) & sin.sin_addr, (void *) hp-> h_addr, hp-> h_length;
/ * Connect to the host * / if (Connect (STRUCK) & SIN, SIZEOF (SIN)) == -1) {Perror ("Connect"); (void) Close (SOCK); RETURN 1);}
Modified IPv6-Aware C C code:
Struct addrinfo * res, * aip; struct addrinfo hints; int suck = -1; int rt error
/ * GET HOST ADDRESS. Any Type of Address Will Do. * / Bzero (& Hints, SizeOf (Hints)); hints.ai_flags = ai_all | ai_addrconfig; hints.ai_socktype = SOCK_STREAM;
Error = GetDrinfo (Hostname, Servicename, & Hints, & res); if (Error! = 0) {(Void) FPRINTF (stderr, "getaddrinfo:% s for host% s service% s / n", gai_strerror (error), hostname , Servicename; Return (-1);} / * try all returned addresses unsteil one works * / for (AIP = Res; AIP! = null; AIP = AIP-> ai_next) {/ * Open socket. The Address Type Depends on what * getaddrinfo () Gave US. * / Sock = Socket (AIP-> Ai_Family, AIP-> AI_SOCKTYPE, AIP-> AI_PROTOCOL); if (SOCK == -1) {Perror ("socket"); FreeAddrinfo RETURN (-1);} / * connect to the host. * / if (connect (SOCK, AIP-> AI_ADDR, AIP-> AI_ADDRLEN) == -1) {PERROR ("Connect"); (Void CLOSE (SOCK); SOCK = -1; Continue;} Break;} FreeAddrinfo (RES);
Note That for new applications, if you write address-family-agnostic data structures, there is no need for porting.
Note: In the new C Socket API, the resolution of the address calls GetDrinfo, the usage of this function, the article in front of Blog summed up
However, when it comes to server-side programming in C / C , there is an additional wrinkle. Namely, depending on whether your application is written for a dual-stack platform, such as Solaris or Linux, or a single-stack platform, Such as Windows, you would need to structure the code diffrendly. For Server-Side Programming, Java Shows A Big Advantage. You Still Write the Same Code as Before:
Serversocket Server = New Serversocket (port); Socket S; While (TRUE) {s = server.accept (); doclientstuff (s);}
NOW, However, if you run the code on an ipv6-enabled machine, you immediately has an ipv6-enabled service.
Here's The Corresponding Server C C code for a dual-stack platform:
int ServSock, csock; struct sockaddr addr, from; ... ServSock = socket (AF_INET6, SOCK_STREAM, PF_INET6); bind (ServSock, & addr, sizeof (addr)); do {csock = accept (ServSocket, & from, sizeof (from )); doClientStuff (csock);} while (finished);! Notice that on a dual-stack machine, since one socket, the IPv6 socket, will be able to access both IPv4 and IPv6 protocol stacks, you only need to create one Socket. Thus this Server CAN Potentially Support Both IPv4 and IPv6 Clients.
Here's The c code for the Same Server for a Single-Stack Platform:
Socket Servsock [fd_setsize]; addrinfo ai0, ai1; servsock [0] = Socket (AF_INET6, SOCK_STREAM, PF_INET6); Servsock [1] = Socket (AF_INET, SOCK_STREAM, PF_INET); ... Bind (Servsock [0], AI0 -> ai_addr, ai0-> ai_addrlen; bind (servsock [1], ai1-> ai_addr, ai1-> ai_addrlen); ... SELECT (2, & Sockset, 0, 0, 0); if (fd_isset (servsocket) 0], & SOCKSET) {// ipv6 connection csock = accept (servsocket [0], (lpsockaddr) & from, fromlen; ...} if (fd_isset (servsocket [1], & sockset) // ipv4 connection csock = Accept (servsocket [1], (lpsockaddr) & from, fromlen; ...}
Here You NEED TO CREATE TWO Server Sockets, One for IPv6 Stack and One for IPv4 Stack. You Also Need To Multiplex On The Two Sockets To Listen To Connections from Either IPv4 OR IPv6 Clients.
Note: Socket client / server programming mode, the client's transplant is relatively simple because the client either is a V4 connection, either V6 connection, even a double stack client, usually does not start simultaneous use of several addresses (Even if the multithreaded download is also a IP, I haven't heard of the multi-IP connection server through a machine, maybe the BT is more like, but it is not entirely, maybe this will happen after the future V6 network. Let's build a connection through V4 and V6, then perform download or anything else operation, it is not difficult to implement it anyway; usually support the double stack when the server is usually established, so it will be established when transplantation Multiple serversockets, the amount of change will be slightly larger.
But it is said that the transplant for C code is physical strength! The technical content is not high, and it is necessary to have enough patience. WITH JAVA You Can Run Any Java Applications, Client or Server, ON AN IPv6-Enabled Platform Using J2SE 1.4 or Later, AND That Application Will Automagically Become IPv6-enabled.
Contrasting this with legacy, native-language application application
How IPv6 Works on A Java Platform
The Java networking stack will first check whether IPv6 is supported on the underlying OS. If IPv6 is supported, it will try to use the IPv6 stack. More specifically, on dual-stack systems it will create an IPv6 socket. On separate-stack systems things are much more complicated. Java will create two sockets, one for IPv4 and one for IPv6 communication. for client-side TCP applications, once the socket is connected, the internet-protocol family type will be fixed, and the extra socket can be closed. for server-side TCP applications, since there is no way to tell from which IP family type the next client request will come, two sockets need to bemaintained. for UDP applications, both sockets will be needed for the lifetime of the communication.
Java Gets The IP Address from a name service.
Details on IPv6 Support in Java
You do not need to know the following in order to use IPv6 in Java. But if you are curious and what to know what happens under various circumstances, the remainder of this document should provide answers.
Special IPv6 Address Types
Unspecified address (:: Corresponding to 0.0.0.0 in IPv4)
This is also called anylocal or wildcard address If a socket is bound to an IPv6 anylocal address on a dual-stack machine, it can accept both IPv6 and IPv4 traffic;. If it is bound to an IPv4 (IPv4-mapped) anylocal address, it can only accept IPv4 traffic. We always try to bind to IPv6 anylocal address on a dual-stack machine unless a related system property is set to use IPv4 Stack.When bound to ::, method ServerSocket.accept will accept connections from both IPv6 OR IPv4 hosts. The Java Platform API Currently Has No Way To Specify To Accept Connections Only from IPv6 Hosts.
Note: Wild address: It is the binding address that Server end programs uses, binds :: address in JDK5.0, the server can accept data from V4 and V6, more convenient, current Java's API has not yet The way name is only accepted only IPv6 connection. After all, IPv4 has a long way, and the transformation of the network is not a chairman.
But usually for wild bindings, it is prone to Socket hijacking, and there is this issue in the early Socket API of Windows, but believes that JDK5.0 should be considered, this problem is to be programmed to be programs.
Applications CAN Enumerate The Interfaces Using NetworkInterface and Bind A Serversocketchannel To Each IPv6 Address, And Then Use A Selector from the New I / O API To Accept Connections from these Sockets.
Note: The Option Discussed Below Is Introducesd In Draft-Ietf-IPNGWG-RFC2553BIS-03.TXT. It Will Be Supported in The Java 2 Platform When IT Becomes A Standard.
However, there is a new socket option that changes the above behaviour. Draft-ietf-ipngwg-rfc2553bis-03.txt has introduced a new IP level socket option, IPV6_V6ONLY. This socket option restricts AF_INET6 sockets to IPv6 communications only. Normally, AF_INET6 sockets may be used for both IPv4 and IPv6 communications. Some applications may want to restrict their use of an AF_INET6 socket to IPv6 communications only. for these applications the IPV6_V6ONLY socket option is defined. When this option is turned on, the socket can be used To send and receive ipv6 packets online. by default this option is turned off.loopback address (: 1 corresponding to 127.0.0.1 in ipv4)
.
IPv4 and IPv6 Addresses Are Separate Address Spaces Except When It comes to "::".
Note: Back to the ring address: 1, usually Fe80 :: 1 is also a local address
CompaticiLity Address :: w.x.y.z
THIS Used for Hosts and Routers to Dynamically Tunnel IPv6 Packets over IPv4 Routing Infrastructure. It is meaningful for OS Kernel and Routers. Java Provides a Utility Method To Test IT.
IPv4-mapped address :: fff: w.x.y.z
This is an IPv6 address that is used to represent an IPv4 address. It allows the native program to use the same address data structure and also the same socket when communicating with and IPv6 nodes both IPv4. Thus, on a dual-stack node with IPv4 -mapped address support, an IPv6 application can talk to both IPv4 and IPv6 peer. The OS will do the underlying plumbing required to send or receive an IPv4 datagram and to hand it to an IPv6 destination socket, and it will synthesize an IPv4-mapped IPv6 address when needed.For Java, it is used for internal representation;... it has no functional role Java will never return an IPv4-mapped address It understands IPv4-mapped address syntax, both in byte array and text representation However, it Will Be Converted INTO AN IPv4 Address.
IPv6-Related System Properties
On Dual Stack Machines, System Properties Are Provided for Setting The Preferred Protocol Stack-IPv4 or IPv6-As Well As The PreferRed Address Family Types-inet4 or inet6.
IPv6 Stack Is Preferred by Default, Since ON A DUAL-Stack Machine IPv6 Socket Can Talk to Both IPv4 and IPv6 Peers.
This setting can be changing through the java.net.preferipv4stack =
By default, we would prefer IPv4 addresses over IPv6 addresses, i.e., when querying the name service (e.g., DNS service), we would return Ipv4 addresses ahead of IPv6 addresses There are two reasons for this choice.:
There area, IPv4 Address Textual Format, IE "% D.% D.% D.% D". Using An IPv4 address minimizes the surprises; using ipv4 address, We can use one call (with an an ipv6 socket) to reach either a legacy IPv4-only service, or an IPv6 service (unless the IPv6 service is on a Ipv6 only node) .This setting can be changed through the system property java.net.preferIPv6Addresses =
Note: When debugging the program, the call to get the address requires the correct settings of the two system properties, otherwise the expected V6 address may not be obtained.
Dual-Stack Node
For many years, if not forever, there will be a mix of IPv6 and IPv4 nodes on the Internet. Thus compatibility with the large installed base of IPv4 nodes is crucial for the success of the transition from IPv4 to IPv6. Dual stack, defined in RFC 1933, is one of the main mechanisms for guaranteeing a smooth transition. The other mechanism is IPv6 packet tunneling, which is relevant to the JDK only through the IPv4-compatible address. The former is the most relevant piece to the JDK. A dual Stack Includes Implementations of Both Versions of The Internet Protocol, IPv4 and IPv6.
A general property of a dual-stack node is that an IPv6 socket can communicate both with an IPv4 and IPv6 peer at the transport layer (TCP or UDP). At the native level, the IPv6 socket communicates with an IPv4 peer through an IPv4- mapped IPv6 address. However, unless a socket checks for the peers address type, it will not know whether it is talking to an IPv4 or an IPv6 peer. All the internal plumbing and conversion of address types is done by the dual-protocol stack .
Note:. IPv4-mapped address has significance only at the implementation of a dual-protocol stack It is used to fake (ie, appear in the same format as) an Ipv6 address to be handed over to an IPv6 socket At the conceptual level. IT HAS NO ROLE; ITS ROLE IS LIMITED AT The Java API Level. Parsing of An IPv4-Mapped Address Is Supported, But An IPv4-mapped Address Is Never Returned.java Application Impact
There should be no change in Java application code if everything has been done appropriately Ie, there are no direct references to IPv4 literal addresses;. Instead, hostnames are used All the address or socket type information is encapsulated in the Java networking API Through.. Setting System Properties, Address Type and / OR Socket Type Preferences Can Be Set. for New Applications IPv6-Specific New Classes and APS Can Be Used.
Communication Scenarios:
(NODES) V4 ONLYV4 / V6V6 Onlyv4 Onlyxx V4 / V6XXXV6 Only XX
..................
UDPSCENARIO 1:
Either Host1 or Host2 Can Be a Native Application.
Host1 is Server, Host2 Is Client
If host2 wants to talk to host1, it will create a V6 socket. It then looks up the IP address for host1. Since host1 only has a v4 protocol stack, it will only have IPv4 records in the name lookup service. So host2 will try To Reach Host1 Using An IPv4-Mapped Address. An IPv4 Packet Will Be Sent By Host2, And Host1 Will Think It Is Communicating With A V4 Client.
Host1 IS Client, Host2 is Server
If host2 is the server, it will first create a v6-type socket (by default), then it will wait for connections. Since host1 supports v4 only, it creates a v4-type socket. They resolves the name for host2. It only gets v4 address for host2, since it does not understand IPv6 address. So it connects to host2 using v4 address. A v4 packet will be sent on the wire. On host2, the dual stack will convert the v4 packet into a v6 packet with A V4-mapped address in it and hand it over to the v6 socket. The Server Application Will Handle IT As if it is a connection from a v6 node.class changes - some parties have an impact
Inetaddress
This class represents an IP address. It provides address storage, name-address translation methods, address conversion methods, as well as address testing methods. In J2SE 1.4, this class is extended to support both IPv4 and IPv6 addresses. Utility methods are added to Check Address Types and scopes. The Two Types of Addresses, IPv4 and IPv6, Can Be distinguided by the java type inet4address and inet6address.
Two new subclasses of InetAddress are created:. Inet4Address and Inet6Address V4- and V6-specific state and behaviors are implemented in these two subclasses Due to Java's object-oriented nature, an application normally only needs to deal with InetAddress class-through polymorphism it. will get the correct behavior. only when it needs to access protocol-family-specific behaviors, such as in calling an IPv6-only method, or when it cares to know the class types of the IP address, will it ever become aware of Inet4Address And inet6address.
The New Methods Introduces
InetAddress: isAnyLocalAddressisLoopbackAddressisLinkLocalAddressisSiteLocalAddressisMCGlobalisMCNodeLocalisMCLinkLocalisMCSiteLocalisMCOrgLocalgetCanonicalHostNamegetByAddrInet6Address: isIPv4CompatibleAddress
Inetaddress and diffrent Naming Services
Prior to 1.4, InetAddress utilized the system configured name service to resolve host names. In 1.4, we have added a Java DNS provider through JNDI for alternative name lookups. You can tell the JDK to use this provider by setting up a few system properties. ................ ..
A Word on Serialization
All IPv4 addresses are represented in Java as Inet4Address objects. They are serialized as InetAddress objects, and deserialized from InetAddress to Inet4Address to keep backward compatibility. IPv6 addresses are represented as Inet6Address and are serialized as such.
Socket, Serversocket, And DataGramsocket
Due to the object-oriented nature of Java, the address types and storage structures are not exposed at the socket API level, so no new APIs are needed. The existing socket APIs handle both IPv4 and IPv6 traffic.
The Selection of Which Stack To Use Depends Upon The Following:
The Underlying OS Support; Bible System Support The User's Stack Preference Property Setting. User Agreement Stack Properties Correct Settings
All supported IPv6 Socket Options Have A IPv4 Counterparts. Thus No New Apis Were Added To Support IPv6 Socket Options. INSTEAD, The Old Apis Area Optioned To Support Both V4 And V6 Socket Options.
MulticastSocket
Again All The Socket Options Apis Are Overloaded to Support IPv6 MultiCast Socket Options.
We have added two new APIs to set / get network interfaces in addition to the existing MulticastSocket.setInterface / MulticastSocket.getInterface that takes / returns an InetAddress instance. The two existing methods are used to set or retrieve the network interface used by the current MulticastSocket to send multicast packets (ie, equivalent to IP_MULTICAST_IF in native socket option). For IPv4, the interface was indicated by an IP address. Thus we can use the equivalent InetAddress in Java. They will continue to work with IPv6 multicast socket. However, in IPv6, according to RFC 2553, the interface should be indicated using an interface index. to better support the concept of a network interface, we introduced a new class, NetworkInterface. It encapsulate the data representing the state of the network interface, including name And IP Addresses and Some Basic Manipulation Methods. Thus we have introduced two new method for multicast Socket: SetNetworki NTERface and getNetworkInterface. They take or return a networkinterface object. There New Methods Can Be Used with Both V4 and v6 multicast. Note: Multicast address definition in V6, FF01 :: 1 Node's multicast address of all nodes in the local area; FF02: 1 Multicast Address of all nodes in the link
.
MulticastSocket: NetworkInterface getNetworkInterface () setNetworkInterface (NetworkInterface netIf) joinGroup (SocketAddress mcastaddr, NetworkInterface netIf) leaveGroup (SocketAddress mcastaddr, NetworkInterface netIf)
URL, URI PARSERS
Literal IP addresses can be used in URL / URIs. However, since colon (:) is used in existing URL / URI specifications to separate host from port, using literal IPv6 representation in URL / URIs without modification will fail in parsing. Thus for specifying LITERAL IPv6 Addresses in URL / URIS, RFC 2732 Was Created. The Parsing of Url / Uri Has Been Updated to Be Compliant with Rfc 2732.SocketperMission
Since SocketPermission Utilizes Urls, ITS IMPLEmentation Has Been Updated to Be Compliant With RFC 2732.
CodeBase, Used in Defining a Permission, IS A Variant of Url. As Such, IT Should Follow Url Formats and Conventions. RFC 2732 Format IS Used for Url and CodeBase; RFC 2373 Format IS Used Everywhere Else.
IPv6 Networking Properties
Java.Net.Preferipv4stack (Default: False)
If IPv6 is available on the operating system, the underlying native socket will be an IPv6 socket. This allows Java (tm) applications to connect too, and accept connections from, both IPv4 andIPv6 hosts.
IF An Application Has A Preference To Only Use IPv4 Sockets, The Property Can Be Set To True. The imphibition is what the application will not becomunicate with ipv6 hosts.
Note: If you do not want to use IPv6, set java.net.preferipv4stack to true, default is V4 / V6 pair support
Java.Net.Preferipv6addresses (Default: False)
If IPv6 is available on the operating system, the default preference is to prefer an IPv4-mapped address over an IPv6 address. This is for backward compatibility reasons-for example, applications that depend on access to an IPv4-only service, or applications that depend on the% d.% d.% d.% d representation of an IP address.This property can be set to try to change the preferences to use IPv6 addresses over IPv4 addresses. This allows applications to be tested and deployed in environments where Note: Note: Note: If you test the IPv6 program, you will be set to true, get the address of V6 when you get the address.
JNDI DNS Service Provider Settings:
Sun.Net.spi.nameservice.Provider.
Specifies the name service provider that you can use. By default, Java will use the system-configured, name-lookup mechanism, such as file, nis, etc. You can specify your own by setting this option.
Sun.net.spi.nameservice.nameservers =
You Can Specify A Comma Separated List of IP Addresses That Point To The DNS Servers You Want To Use.
Sun.net.spi.nameservice.domain =
This Property Specifier The Default DNS Domain Name, E.G., Eng.sun.com.
Wang Jianbai Email: WJB @ nlsde. Buaa.edu.cn North Air Technology Software Development Environment National Key Laboratory