一、由域名求IP地址的程序
下面程序由命令行输入域名,输出ip
import java.net.*;
public class nslookup {
//Usage:java nslookup hostname
public static void main (String argv[]) throws Exception {
String host=argv[0];
InetAddress address=null;
try {
address=InetAddress.getByName(host);
} catch(UnknownHostException e) {
System.out.println("Unknown host");
System.exit(0);
}
byte[] ip=address.getAddress();
for (int i=0;i< ip.length;i++) {
if (i>0) System.out.print(".");
System.out.print(ip[i]&0xff);
}
System.out.println();
}
}
程序运行结果:
C:\java>java nslookup sina.com
71.5.7.138
C:\java>
二、 得到某个域名的所有IP地址
import java.net.*;
import java.io.*;
public class SimpleDNS
{
public static void main(String[] args)
{
try
{
InetAddress[] address =InetAddress.getAllByName("www.sina.com");
for(int i=0;i< address.length;i++)
{
System.out.println(address[i].getHostAddress());
}
}
catch (Exception e)
{
System.out.println(e.toString());
System.exit(1);
}
}
}
?
运行结果:
C:\java>java SimpleDNS www.s
218.30.13.35
218.30.13.36
218.30.13.37
218.30.13.38
218.30.13.39
218.30.13.40
218.30.13.41
218.30.13.42
218.30.13.43
218.30.13.44
218.30.13.45
218.30.13.46
218.30.13.47
218.30.13.48
218.30.13.49
218.30.13.34
三、 IP地址转换成10进制整数
经常要判断一个ip是国内的还是国外的,有了下面程序再结合数据库查询...
public class IP
{
private static long ipToLong(String strIP)
//将127.0.0.1 形式的IP地址转换成10进制整数,这里没有进行任何错误处理
{
int j=0;
int i=0;
long [] ip=new long[4];
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];
}
private static String longToIP(long longIP)
//将10进制整数形式转换成127.0.0.1形式的IP地址
{
StringBuffer sb=new StringBuffer("");
sb.append(String.valueOf(longIP>>>24));//直接右移24位
sb.append(".");
//将高8位置0,然后右移16位
sb.append(String.valueOf((longIP&0x00FFFFFF)>>>16));
sb.append(".");
sb.append(String.valueOf((longIP&0x0000FFFF)>>>8));
sb.append(".");
sb.append(String.valueOf(longIP&0x000000FF));
sb.append(".");
return sb.toString();
}
public static void main(String[] args)
{
System.out.println("IP地址的各种表现形式:\r\n");
System.out.print("32位二进制形式:");
System.out.println(Long.toBinaryString(3526601384L));
System.out.print("十进制形式:");
System.out.println(ipToLong("210.51.170.168"));
System.out.print("普通形式:");
System.out.println(longToIP(3526601384L));
}
}
程序运行结果:
IP地址的各种表现形式:
32位二进制形式:11001010011100000110000010100011
十进制形式:3396362403
普通形式:202.112.96.163.