码迷,mamicode.com
首页 > 编程语言 > 详细

java网络基本类使用(一)

时间:2016-05-05 15:56:53      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

1.怎么获取ip相关信息

 1 import java.net.InetAddress;
 2 import java.net.NetworkInterface;
 3 import java.util.Enumeration;
 4 
 5 
 6 
 7 public class Test {
 8 
 9     public static void main(String[] args) throws Exception{
10         
11         java.net.InetAddress address=InetAddress.getByName("www.baidu.com");
12         System.out.println(address.getHostName());
13         System.out.println(address.getHostAddress());
14         
15         InetAddress[] addresss=InetAddress.getAllByName("www.baidu.com");
16         for(InetAddress a : addresss){
17             System.out.println(a);
18         }
19         
20         InetAddress localAddress=InetAddress.getLocalHost();        
21         System.out.println(localAddress);
22         
23         //判断IP地址
24         byte[] addressByte=localAddress.getAddress();
25         if(addressByte.length==4){
26             System.out.println("这个是ip4地址!");
27         }else if(addressByte.length==16){
28             System.out.println("这个是ip6地址!");
29         }else{
30             System.out.println("未知地址...");
31         }
32         
33         NetworkInterface netInterface=NetworkInterface.getByInetAddress(localAddress);
34         System.out.println(netInterface);
35         
36         //获取所有的网络接口
37         Enumeration<NetworkInterface> netInNetworkInterface=NetworkInterface.getNetworkInterfaces();
38         while(netInNetworkInterface.hasMoreElements()){
39             NetworkInterface ni=netInNetworkInterface.nextElement();
40             System.out.println(ni);
41         }
42     }
43     
44 }

 

java网络基本类使用(一)

标签:

原文地址:http://www.cnblogs.com/huzi007/p/5462088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!