码迷,mamicode.com
首页 > Web开发 > 详细

InetAddress 对象的实例方法

时间:2014-11-21 12:16:29      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   java   for   

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 对象的实例方法

标签:style   blog   io   ar   color   os   sp   java   for   

原文地址:http://www.cnblogs.com/starzou/p/4112232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!