Using Java to develop IPV6-compatible Web applications

Source: Internet
Author: User



Depending on the deployment speed of the existing IPV4 address, the remaining address will be exhausted in 10-20 years. Therefore, the network gradually from IPV4 to IPv6 conversion is inevitable, the corresponding various network applications will support IPV6. For Java, starting from its 1.4 version of the IPV6 to provide better support, the programmer has basically shielded the differences between IPV4 and IPV6, but there are still some IPv6 caused by the changes we need to deal with carefully. In this case, this article describes how to use the existing Java technology to address these changes.


IPV6 Background Introduction


At present, we are using the second generation of Internet IPv4 technology, its biggest problem is the network Address resource is limited, theoretically speaking, can address 16 million networks, 4 billion hosts. However, after adopting the type A, B and C Three, the number of available network address and host address is greatly reduced, and the current IP address is nearly exhausted. The lack of network address seriously restricts the application and development of the global Internet.



On the one hand is the limit of the number of address resources, on the other hand, along with the development of electronic technology and network technology, the computer network will enter People's daily life, may be around every thing need to connect to the global Internet. In this environment of lack of network space, IPv6 was born. It not only solves the problem of the number of network address resources, but also clears the limit of the number of devices connected to the Internet in addition to computers.



If the IPV4 realization of the only man-machine dialogue, then IPv6 extension to any of the conversations between things, it can not only serve the human service, will also serve a number of hardware equipment, such as household appliances, sensors, remote cameras, cars, etc., it will be no time, everywhere in the deep society every corner of the real broadband network, The economic benefits it brings will also be enormous.



Of course, IPV6 is not perfect, once and for all, impossible to solve all problems. IPV6 can only be perfected in the development, can not happen overnight, the transition takes time and cost, but in the long run, IPv6 is conducive to the continuous and long-term development of the Internet. At present, the Internet organization has decided to set up two specialized working groups to develop the corresponding international standards.





Java Support for IPV6


With IPv6 increasingly valued by the industry, Java has supported the IPV6 on Linux and Solaris platforms since version 1.4. Support on the Windows platform has been added since version 1.5. The changes in IPV4 and IPV6 are well encapsulated relative to C++,java, and legacy code can natively support IPv6 without changing with the underlying specific implementation.



So how does Java support IPV6? The Java network stack will prioritize whether the underlying system supports IPV6 and what IP stack systems are used. If it is a dual-stack system, it creates a IPv6 socket (1) directly.


Figure 1. Double stack Structure





For the split stack system, Java creates a ipv4/v6 two sockets (2). In the case of a TCP client, if one of the sockets is successfully connected, the other socket is closed and the IP protocol type used by the socket connection is fixed. If it is a TCP server-side program, IPV4/V6 two sockets will be retained because the IP protocol used by the client cannot be expected. For UDP applications, either the client or the server-side program, two sockets are retained to complete the communication.


Figure 2. Split stack structure







How to verify IPV6 address IPV6 address representation


The most significant change from IPV4 to IPv6 is the length of the network address, the IPV6 address is 128-bit length, typically 32 hexadecimal digits, but is usually written in 8 groups of 4 hexadecimal forms per group. For example:



2001:0db8:85a3:08d3:1319:8a2e:0370:7344 is a valid IPV6 address. If four numbers are zero, they can be omitted.



2001:0db8:85a3:0000:1319:8a2e:0370:7344 is equivalent to 2001:0db8:85a3::1319:8a2e:0370:7344.



Following these rules, if more than two colons appear because of the omission, you can compress to one, but this zero compression appears only once in the address. So:


2001:0DB8:0000:0000:0000:0000:1428:57ab
2001:0DB8:0000:0000:0000::1428:57ab
2001:0DB8:0:0:0:0:1428:57ab
2001:0DB8:0::0:1428:57ab
2001:0DB8::1428:57ab


are valid addresses, and they are equivalent. But the 2001::25de::cade is illegal. (because it makes it unclear how many all zeros are grouped in each compression). At the same time the leading 0 can be omitted, therefore: 2001:0db8:02de::0e13 equals 2001:db8:2de::e13.


IPV6 address Check


The IPV4 address can be easily converted to the IPV6 format. For example, if an address of IPV4 is 135.75.43.52 (16 binary is 0x874b2b34), it can be converted to 0000:0000:0000:0000:0000:0000:874b:2b34 or:: 874b:2b34. You can also use the mixed symbol (ipv4-compatible address), which can be: 135.75.43.52.



To develop Java applications in a IPV6 environment, or to migrate Java applications developed in an existing IPV4 environment into IPV6 environments, validation of IPV6 network addresses is a necessary step, especially for Java applications that provide UI (user interfaces).



Fortunately, since Java 1.5, Sun has added Java support for IPV6 network address checking. Programmers can verify that a String type of input is a legitimate IPV6 network address by simply calling Method Sun.net.util.IPAddressUtil.isIPv6LiteralAddress ().



To further understand IPV6 's network address specification and its validation algorithm, I refer to some materials, including the source code of the method sun.net.util.IPAddressUtil.isIPv6LiteralAddress () described above, And the regular expression of some IPV6 network addresses circulating on the network, found that:


    1. Because the IPV6 protocol allows more network address format, the specification is looser (for example, 0 compressed address, IPV4 mapping address, etc.), so the format of the IPV6 network address varies greatly.

    2. Java's validation of IPV6 network addresses is done by looping through the input characters, and does not take a regular expression approach. The matching process also relies on other Java methods.

    3. The regular expression of IPV6 network address verification, which is circulated on the network, usually covers only part of the address format, and the expression is lengthy and difficult to read, which is not easy to understand.


Based on universality considerations, and in order to make the verification method as easy as possible to read, the author attempts to classify the IPV6 network address in a simple way, using multiple regular expressions to verify.



This approach takes into account versatility (based on regular expressions, so it is easy to implement in a variety of programming languages), as well as legibility (each independent regular expression is relatively short), and according to the test, all current IPV6 network address format types are supported and no exceptions have been found.



The following is a method of verifying the IPV6 network address written by the author in Java. This algorithm can be easily rewritten in other programming languages.


Listing 1. Verify Address
 
//IPv6 address validator matches these IPv6 formats
//::ffff:21:7.8.9.221 | 2001:0db8:85a3:08d3:1319:8a2e:0370:7344 
//| ::8a2e:0:0370:7344 | 2001:0db8:85a3:08d3:1319:8a2e:100.22.44.55 
//| 2001:0db8::8a2e:100.22.44.55 | ::100.22.44.55 | ffff::
//And such addresses are invalid
//::8a2e:0:0370:7344.4 | 2001:idb8::111:7.8.9.111 | 2001::100.a2.44.55 
//| :2001::100.22.44.55 
public static boolean isIPV6Format(String ip) {
    ip = ip.trim();

    //in many cases such as URLs, IPv6 addresses are wrapped by []
    if(ip.substring(0, 1).equals("[") && ip.substring(ip.length()-1).equals("]")) 
    
        ip = ip.substring(1, ip.length()-1);

        return (1 < Pattern.compile(":").split(ip).length)
	    //a valid IPv6 address should contains no less than 1, 
	    //and no more than 7 “:” as separators
            && (Pattern.compile(":").split(ip).length <= 8) 

	    //the address can be compressed, but “::” can appear only once
            && (Pattern.compile("::").split(ip).length <= 2) 

	    //if a compressed address
            && (Pattern.compile("::").split(ip).length == 2) 

            //if starts with “::” – leading zeros are compressed
            ? (((ip.substring(0, 2).equals("::"))  
            ? Pattern.matches("^::([\\da-f]{1,4}(:)){0,4}(([\\da-f]{1,4}(:)[\\da-f]{1,4})
	    |([\\da-f]{1,4})|((\\d{1,3}.){3}\\d{1,3}))", ip)
                : Pattern.matches("^([\\da-f]{1,4}(:|::)){1,5}
		(([\\da-f]{1,4}(:|::)[\\da-f]{1,4})|([\\da-f]{1,4})
		|((\\d{1,3}.){3}\\d{1,3}))", ip)))

		//if ends with "::" - ending zeros are compressed
                : ((ip.substring(ip.length()-2).equals("::"))  
                ? Pattern.matches("^([\\da-f]{1,4}(:|::)){1,7}", ip)
                : Pattern.matches("^([\\da-f]{1,4}:){6}(([\\da-f]{1,4}
		:[\\da-f]{1,4})|((\\d{1,3}.){3}\\d{1,3}))", ip));
    }}




How to normalize IPV6 addresses


In the development of network programs, IP addresses are often used to identify a host, such as recording the Access records of an end user. Because IPV6 has a number of representations, such as 0 compressed addresses, it may be problematic to use the IPV6 address as the identifier directly. To avoid these problems, it is necessary to formalize the IPV6 address before using it. In addition to our well-known regular expressions, the author finds that using a simple Java API can achieve the same result in the development process.


Listing 2. Normalized address
 
InetAddress inetAddr = InetAddress.getByName(ipAddr); 
ipAddr = inetAddr.getHostAddress(); 
System.out.println(ipAddr);


InetAddress.getByName(String)Method accepts a parameter that can be either a host name or an IP address string. ThegetHostAddress()address string ipaddr has been converted to full form when we enter the legal IPV6 address of any information and then remove the host IP by method. For example2002:97b:e7aa::97b:e7aa, after the above code is executed, the 0 compression will be restored and ipaddr become2002:97b:e7aa:0:0:0:97b:e7aa.



Back to top of page


How to get the native IPV6 address


Sometimes in order to be able to register listener, developers need to use the native IPV6 address, this address can not be easily obtained through Inetaddress.getlocalhost (). Because it is possible to obtain a special address such as 0:0:0:0:0:0:0:1. With such an address, other servers will not be able to send notifications to this machine, so you must first filter to select the addresses that are actually available. The following code implements this function by traversing the various addresses of the network interface until the required address is found.


Listing 3. Get the native IP address
 
public static String getLocalIPv6Address() throws IOException {
    InetAddress inetAddress = null;
    Enumeration<NetworkInterface> networkInterfaces = NetworkInterface
        .getNetworkInterfaces();
    outer: 
    while (networkInterfaces.hasMoreElements()) {
        Enumeration<InetAddress> inetAds = networkInterfaces.nextElement()
	    .getInetAddresses();
        while (inetAds.hasMoreElements()) {
            inetAddress = inetAds.nextElement();
            //Check if it‘s ipv6 address and reserved address
            if (inetAddress instanceof Inet6Address 
                && !isReservedAddr(inetAddress)) {
                break outer;
            }
        }
    }

    String ipAddr = inetAddress.getHostAddress();
    // Filter network card No
    int index = ipAddr.indexOf(‘%‘);
    if (index > 0) {
        ipAddr = ipAddr.substring(0, index);
    }

    return ipAddr;
}

/**
 * Check if it‘s "local address" or "link local address" or
 * "loopbackaddress"
 * 
 * @param ip address
 * 
 * @return result
 */
private static boolean isReservedAddr(InetAddress inetAddr) {
    if (inetAddr.isAnyLocalAddress() || inetAddr.isLinkLocalAddress()
        || inetAddr.isLoopbackAddress()) {
        return true;
    }

    return false;
}


To support the addition of two inetaddress subclasses in Ipv6,java: Inet4address and Inet6address. In general, these two subclasses are not used, but are useful when we need to handle different IP protocols separately, where we filter addresses based on inet6address.



The Isreservedaddr () method filters the native special IP addresses, including "LocalAddress", "linklocaladdress", and "loopbackaddress". Readers can modify the filtering criteria according to their own needs.



Another note: On the Windows platform, the IPV6 address may be followed by a percent semicolon plus a number. The number here is the number of the native network adapter. This suffix is not part of the IPV6 standard address and can be removed.



Back to top of page


Ipv4/ipv6, network selection and testing in dual environment


Let's take a look at the author's Ipv4/ipv6 development test environment and how to configure it.



The author's Ipv4/ipv6 dual environment is a typical "6to4" dual-stack network, in which there is a IPv6 to IPV4 mapping mechanism, that is, any one IPV6 address 2002:92a:8f7a:100:a:b:c:d in the route will be mapped by default to IPV4 address A.B.C.D, so the routing table has only one set.



In this environment, the IPV4 address and the IPV6 address of one by one correspond to the manual guarantee. If a client uses mismatched IPV4 and IPV6 dual addresses, or both DHCPV4 and DHCPv6 (which could cause a IPv4 address and a IPV6 address mismatch), the IPV6 's routed addressing will fail.



Because of this, in order to configure the dual address environment, we generally use DHCPv4 to get the IPV4 address, and then manually configure the corresponding IPV6 address.



Windows system


    • Windows 2000 and below: IPV6 not supported

    • Windows 2003 and Windows XP: Add IPV6 addresses and DNS by using the Netsh command line that comes with Windows, for example: C:\>netsh interface ipv6 add address "Local Ar EA Connection "2002:92a:8f7a:100:10:13:1:2 and C:\>netsh interface ipv6 add DNS" Local area Connection "2002:92a:8f7a:100 : 10::250

    • Windows 2008 and Windows Vista: can be configured either by using the Windows Network Properties page or by using the Netsh command line like Windows 2003 and Windows XP


Linux System (The following is the temporary configuration method of IPv6, that is, the configuration file is not modified, the configuration fails after the computer restarts)


    • Redhat Linux: The simplest approach is to add IPV6 addresses using the ifconfig command line, for example: Ifconfig eth0 inet6 add 2002:92a:8f7a:100:10:14:24:106/96.

    • SUSE Linux: Ibid.


In practice, because of the object-oriented nature of Java and the good encapsulation of the IP address of the java.net package, the porting of Java applications from the IPV4 environment to the Ipv4/ipv6 dual environment, or the pure IPV6 environment becomes surprisingly simple. Usually all we need to do is to check the code and remove the IPV4 address written in the plaintext, instead of the host name.



In addition, for some special needs, Java also provides two extension classes of inetaddress for use: Inet4address and inet6address, which encapsulate special properties and behaviors for IPv4 and IPv6. However, due to the polymorphic nature of Java, programmers generally only need to use the parent class Inetaddress,java virtual machines can choose the correct behavior logic at runtime depending on the type of IP address being encapsulated. So in most cases, programmers do not need to control exactly what type and behavior they are using, and everything is given to the Java virtual machine.



Please refer to Sun's JAVADOC for specific new types and how to add them.



In addition, the following two IPV6-related Java Virtual machine System properties are worth noting in the Ipv4/ipv6 dual environment for Web applications developed with Java.


Java.net.preferipv4stack=<true|false> java.net.preferipv6addresses=<true|false>


Preferipv4stack (False by default) indicates whether the Java program takes precedence over IPV4 sockets if there are IPv4 and IPv6 dual stacks. The default value is to use the IPV6 socket first, because the IPV6 socket can talk to the corresponding IPv4 or IPV6 host, whereas if you prefer IPv4, you cannot communicate with the IPV6 host.



Preferipv6addresses (False by default) indicates whether the Java program returns the IPV6 address preferentially if there are IPv4 and IPV6 dual addresses when querying local or remote IP addresses. Java defaults back to IPV4 addresses primarily for backwards compatibility to support legacy IPV4 validation logic, as well as legacy services that only support IPV4 addresses.



?


Summarize


From the development of computer technology, the law of the Internet and the transmission rate of the network, IPV4 are not applicable. The main problem is that IPV4 's 32-bit IP address space cannot meet the rapidly expanding size of the Internet, but the introduction of IPV6 has solved the problem of near-depletion of IP addresses. This article has made some basic introduction to IPV6 address, emphatically introduced how to use Java to develop compatible IPV6 network application program, including how to verify IPV6 address, how to formalize IPv6 address, how to get the address of native IPv6, and in Ipv4/ipv6 dual address environment Network selection and testing, at the same time the author combined with the use of Java code Snippets in daily work, hope to present to the reader a full range of strong practical text introduction, but also hope that this article to the reader in the future use of Java to develop IPV6-compatible program of the process to bring some help.



Developing network applications that are compatible with IPV6 using Java


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.