首页 > 代码库 > InetAddress 对象的实例方法

InetAddress 对象的实例方法

import java.net.Inet4Address;import java.net.Inet6Address;import java.net.InetAddress;import java.net.UnknownHostException;public class InetAddressMethod {            public static void main(String[] args) {                InetAddressMethod inetaddr = new InetAddressMethod();        inetaddr._getHostAddress();        inetaddr._getAddress("www.csdn.net");                InetAddressMethod._getIpType("00::01");    }        public void _getHostAddress() {                InetAddress ipv4Address1 = null;        try {            ipv4Address1 = InetAddress.getByName("1.2.3.4");        } catch (UnknownHostException e) {            e.printStackTrace();        }                System.out.println(ipv4Address1);        System.out.println(ipv4Address1.getHostAddress());    }            public void _getAddress(String hostname) {                InetAddress address = null;        try {            address = InetAddress.getByName(hostname);        } catch (UnknownHostException e) {            e.printStackTrace();        }                byte[] ip = address.getAddress();        for(byte ipSegment : ip) {            System.out.print(ipSegment + ".");        }        System.out.println("");                for(byte ipSegment : ip) {            int newIPSegment = (ipSegment < 0) ? (256 + ipSegment) : ipSegment;            System.out.print(newIPSegment + ".");        }    }            public static void _getIpType(String hostname) {                InetAddress address = null;        try {            address = InetAddress.getByName(hostname);        } catch (UnknownHostException e) {            e.printStackTrace();        }        System.out.println(address.getHostAddress());                switch(address.getAddress().length)        {            case 4:                System.out.println("ipv4 address!");                break;            case 16:                System.out.println("ipv6 address!");                break;        }                if(address instanceof Inet4Address) {            System.out.println("ipv4 address!");        }        if(address instanceof Inet6Address) {            System.out.println("ipv6 address!");        }    }}

 

InetAddress 对象的实例方法