首页 > 代码库 > InetAddress类

InetAddress类

 

 1 import java.net.*; 
 2 public class IPAddressTest{ 
 3     public static void main(String[] args){ 
 4         try{ 
 5             //获得本机的InetAddress信息 
 6             InetAddress IP = InetAddress.getLocalHost(); 
 7             showInfo(IP); 
 8             
 9             //从名字获得 InetAddress信息 
10             IP = InetAddress.getByName("www.sina.com.cn"); 
11             showInfo(IP); 
12             
13             //从IP 地址 获得 InetAddress信息 
14             byte[] bs = new byte[]{(byte)61,(byte)172,(byte)201,(byte)194}; 
15             IP = InetAddress.getByAddress(bs); 
16             showInfo(IP); 
17         } 
18         catch(java.net.UnknownHostException e){ 
19             e.printStackTrace(); 
20         } 
21     } 
22     //将InetAddress 中的信息显示出来 
23     public static void showInfo(InetAddress IP){ 
24         String name = IP.getHostName(); 
25         String address = IP.getHostAddress(); 
26         System.out.println(name); 
27         System.out.println(address); 
28         System.out.println("------------------------------"); 
29     } 
30 }