首页 > 编程语言 > 详细

java-ip的string和long转换

时间:2015-04-24 19:28:43      阅读:172      评论:0      收藏:0      [点我收藏+]
package p1;
import java.net.InetAddress;
public class testIp {
    
    public static void main(String[] args) throws Exception
    {
        
        System.out.println(convertIPToLong("124.74.26.54"));
        System.out.println(convertLongToIP(2085231158));
        
    }
    
    public static long convertIPToLong(String ip) throws Exception
    {
        
        InetAddress IPAddr = InetAddress.getByName(ip);
        if(IPAddr == null)
            return 0L;
        byte bytes[] = IPAddr.getAddress();
        if(bytes.length < 4)
        {
            return 0L;
        } 
        else
        {
            long l0 = bytes[0] & 255;
            long l1 = bytes[1] & 255;
            long l2 = bytes[2] & 255;
            long l3 = bytes[3] & 255;
            return l0 << 24 | l1 << 16 | l2 << 8 | l3;
        }
    }
    
    public static String convertLongToIP(long ipInJava) throws Exception
    {
        
        byte bytes[] = new byte[4];
        bytes[0] = (byte)(int)((ipInJava >> 24) % 256L);
        bytes[1] = (byte)(int)((ipInJava >> 16) % 256L);
        bytes[2] = (byte)(int)((ipInJava >> 8) % 256L);
        bytes[3] = (byte)(int)(ipInJava % 256L);
        InetAddress IPAddr = InetAddress.getByAddress(bytes);
        return IPAddr.getHostAddress();
  }
    
}


java-ip的string和long转换

原文:http://smileyes.blog.51cto.com/6027700/1638034

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!