您的位置:首页 > 编程语言 > Java开发

java-ip的string和long转换

2015-04-24 16:20 19 查看
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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: