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!");
        }
    }
}

 

posted on 2014-11-21 10:33  starzou  阅读(401)  评论(0编辑  收藏  举报

导航