IPV6 BASIC Programming--java

Source: Internet
Author: User
Tags getmessage

IPV6 programming--java1. Java Support IPV6

Java has supported IPV6 on Linux and Solaris platforms starting with version 1.4. Support on the Windows platform has been added since version 1.5.
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).

2. 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.

Package Com.text;import Java.io.ioexception;import Java.net.inet6address;import java.net.inetaddress;import Java.net.networkinterface;import Java.util.enumeration;public class Get_ipv6 {public static void main (string[] args) t        Hrows ioexception{String str = getlocalipv6address ();    System.out.println (str);        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; } private static Boolean isreservedaddr (InetAddress inetaddr) {if (inetaddr.isanylocaladdress () | | | inetaddr.isl Inklocaladdress () | |    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". 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.

3. Ipv4/ipv6 dual environment, network selection and testing

Java 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 the Ipv4/ipv6 dual environment, the following two IPV6-related Java Virtual machine System properties are notable for Web applications developed using Java.
Java.net.preferipv4stack=<\true|false>
Java.net.preferipv6addresses=<\true|false>
The setup code in the program is as follows:
System.setproperty ("Java.net.preferIPv6Addresses", "true");
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.

4. Socket Support IPV6 Communication example

Client:

Package Com.text2;import Java.io.bufferedreader;import Java.io.datainputstream;import java.io.DataOutputStream; Import Java.io.ioexception;import Java.io.inputstreamreader;import Java.net.inet6address;import Java.net.inetaddress;import Java.net.networkinterface;import Java.net.socket;import Java.util.Enumeration;public Class Click {public static void main (string[] args) throws IOException {//Get native IPV6 address getlocalipv6address () method on top        Already mentioned String servernamestring = Getlocalipv6address ();        SYSTEM.OUT.PRINTLN ("Client-initiated ...");        SYSTEM.OUT.PRINTLN ("The client terminates \ n" When receiving the server-side character as \ "Ok\");            while (true) {socket socket = NULL;                try {//creates a stream socket and connects it to the specified port number on the specified host socket = new socket (servernamestring, 8080);                Read server-side data datainputstream input = new DataInputStream (Socket.getinputstream ()); Send data to server side dataoutputstream out = new DataOutputStream (socket.getoutputstream());                System.out.print ("Please enter: \ t");                String str = new BufferedReader (new InputStreamReader (system.in)). ReadLine ();                Out.writeutf (str);                String ret = Input.readutf ();                SYSTEM.OUT.PRINTLN ("The server side returned is:" + ret);                    if ("OK". Equals (ret)) {SYSTEM.OUT.PRINTLN ("the client will close the connection");                    Thread.Sleep (500);                Break                } out.close ();            Input.close ();            } catch (Exception e) {System.out.println ("Client exception:" + E.getmessage ());                    } finally {if (socket! = NULL) {try {socket.close ();                        } catch (IOException e) {socket = null;                    SYSTEM.OUT.PRINTLN ("Client finally exception:" + E.getmessage ()); }}}}} 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; } private static Boolean isreservedaddr (InetAddress inetaddr) {if (inetaddr.isanylocaladdress () | | | inetaddr.islinklocaladdress () | | | inetaddr.isloopbackaddress (            ) {return true;    } return false; }}

Server-side:

Package Com.text2;import Java.io.bufferedreader;import Java.io.datainputstream;import java.io.DataOutputStream; Import Java.io.inputstreamreader;import Java.net.serversocket;import Java.net.socket;public class Server {public stat        IC void Main (string[] args) {//TODO auto-generated Method Stub System.out.println ("Server start ... \ n");        Server server = new server ();    Server.init ();            } public void Init () {try {serversocket serversocket = new ServerSocket (8080);                while (true) {///Once there is a blockage, the server and the client get a connection Socket client = Serversocket.accept ();            Handle this connection with the new Handlerthread (client);        }} catch (Exception e) {System.out.println ("Server exception:" + E.getmessage ());        }} Private class Handlerthread implements Runnable {private socket socket;            Public Handlerthread (socket client) {socket = client; New Thread (this). StarT (); public void Run () {try {//Read client data DataInputStream input = new DATAINP                Utstream (Socket.getinputstream ());                String clientinputstr = Input.readutf (); Here to pay attention to the client output stream corresponding to the Write method, otherwise it will throw eofexception//Processing client Data System.out.println ("The client sent over the content:" + clientin                PUTSTR);                Reply message to client dataoutputstream out = new DataOutputStream (Socket.getoutputstream ());                System.out.print ("Please enter: \ t");                Send keyboard input a line of String s = new BufferedReader (new InputStreamReader (system.in)). ReadLine ();                Out.writeutf (s);                Out.close ();            Input.close ();            } catch (Exception e) {System.out.println ("Server Run Exception:" + E.getmessage ());                    } finally {if (socket! = NULL) {try {socket.close (); } catch (Exception e) {socket = null;                    SYSTEM.OUT.PRINTLN ("Server End finally Exception:" + E.getmessage ()); }                }            }        }    }}

<wiz_tmp_tag id= "Wiz-table-range-border" contenteditable= "false" style= "Display:none;" >

IPV6 BASIC Programming--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.