import java.net.*;
public class GetIp {
public static int isInnerIP(long a_ip)//检查ip地址是否是内网ip
{
int bValid = -1;
if ((a_ip >> 24 == 0xa) || (a_ip >> 16 == 0xc0a8) || (a_ip >> 22 == 0x2b0))
{
bValid = 0;
}
return bValid;
}
// 将127.0.0.1 形式的IP地址转换成10进制整数,这里没有进行任何错误处理
public static long ipToLong(String strIP)
{
long[] ip = new long[4];
//先找到IP地址字符串中.的位置
int position1 = strIP.indexOf(".");
int position2 = strIP.indexOf(".", position1 + 1);
int position3 = strIP.indexOf(".", position2 + 1);
//将每个.之间的字符串转换成整型
ip[0] = Long.parseLong(strIP.substring(0, position1));
ip[1] = Long.parseLong(strIP.substring(position1 + 1, position2));
ip[2] = Long.parseLong(strIP.substring(position2 + 1, position3));
ip[3] = Long.parseLong(strIP.substring(position3 + 1));
return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
}
public static void main(String[] args) {
String ip;
try
{
InetAddress in = InetAddress.getLocalHost();
InetAddress[] all = InetAddress.getAllByName(in.getHostName());
//通过本机主机名,遍历多个ip
for (int i = 0; i < all.length; i++)
{
String tmp=null;
tmp=ip=all[i].getHostAddress().toString();
System.out.println("IP = " +tmp);//输出计算机所有的ip地址
if (isInnerIP(ipToLong(tmp)) == -1)//检查是不是外网ip,如果是就保存文件
{
/*WriteFile(ip);//将ip地址写入文件
System.out.println("IP保存在同目录IP.txt文件中");
System.out.println("同目录IP.txt文件中的IP是:" + ReadFile());*/
System.out.println(ip);
}
}
}
catch (UnknownHostException e)
{
System.out.println(e.getMessage());
}
}
}