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

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。