Java Network Programming from entry to mastery (10): Inet4Address class and Inet6Address class

Source: Internet
Author: User

To differentiateIPv4AndIPv6Address,JavaTwo classes are provided:Inet4AddressAndInet6Address, They are allInetAddressClass subclass. The definitions of these two classes are as follows:
Public Final ClassInet4AddressExtendsInetAddress
Public Final ClassInet6AddressExtendsInetAddress

The two classes areIPv4AndIPv6The rule is implementedInetAddressClassPublicMethod. What they are different from isInet6AddressAnalogyInet4AddressClass has one more method:IsIPv4CompatibleAddressThis method is used to determineIPv6Whether the address andIPv4Address compatibility. AndIPv4CompatibleIPv6Except for the last four bytes, the address has a value name.0, Such0: 0: 0: 0: 0: 0.192.168.18.10,: ABCD: FAFABoth andIPv4CompatibleIPv6Address.

When usingInetAddressClass Four static method creationInetAddressObject, you can useGetAddressReturnedByteArray to determine thisIPThe address isIPv4OrIPv6Address (ByteThe array length is4YesIPv4Address,ByteThe array length is16YesIPv6Address), you can also setInstanceofTo confirmInetAddressThe object is an instance of its subclass. The following codeDemonstrate how to determineIPThe address isIPv4OrIPv6Address:

Package Mynet;

Import Java.net. * ;

Public   Class MyIP
{
Public   Static   Void Main (String [] args) Throws Exception
{
If (Args. length =   0 )
Return ;
InetAddress address = InetAddress. getByName (args [ 0 ]);
System. out. println ( " IP: "   + Address. getHostAddress ());
Switch (Address. getAddress (). length)
{
Case   4 :
System. out. println ( " Determine whether the IP address is an IPv4 address based on the length of the byte array! " );
Break ;
Case  

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.