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