利用Java获取IP地址(整理)
2012-03-09 12:33
351 查看
package ipDemo; import java.io.File; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; public class GetIpAddress { public static void main(String[] args) { if(args.length==0){ printLocalInfo(); }else{ printInputInfo(args); } } /** *获取本地IP */ static void printLocalInfo(){ try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); if(interfaces == null){ System.out.println("There isn't network interface!"); }else{ while(interfaces.hasMoreElements()){ NetworkInterface interInfo = interfaces.nextElement(); System.out.println("Interface:"+interInfo.getName()+"--"); Enumeration<InetAddress> addressEnum = interInfo.getInetAddresses(); if(!addressEnum.hasMoreElements()){ System.out.println("\t(No address for this interface)"); } while(addressEnum.hasMoreElements()){ InetAddress address = addressEnum.nextElement(); String str =null; if(address instanceof Inet4Address){ str = "(IPv4)"; }else if(address instanceof Inet6Address){ str = "(IPv6)"; }else{ str = "(?)"; } System.out.print("\tAddress "+str); System.out.println(File.separator+address.getHostAddress()); } } } } catch (SocketException se) { System.out.println("NetWork interface error:"+se.getMessage()); } } /** *获取输入信息的IP */ static void printInputInfo(String[] args){ for(String host:args){ try { System.out.println(host+":"); InetAddress[] addressArray = InetAddress.getAllByName(host); for(InetAddress address:addressArray){ System.out.println("\t"+address.getHostName()+File.separator +address.getHostAddress()); } } catch (UnknownHostException e) { System.out.println("\tUnable to find address for "+host); } } } }
相关文章推荐
- Java利用Request请求获取IP地址的方法详解
- Java利用Request请求如何获取IP地址对应的省份、城市详解
- 【Servlet】Javaweb中,利用新浪api接口,获取IP地址,并获取相应的IP归属地
- 利用java获取本机IP地址的方法
- 用Java来获取访问者真实的IP地址
- MAC地址,使用java获取IP地址和MAC地址。
- Java获取网络上主机的IP地址
- Java 各种路径获取方式整理
- java获取指定的主机的IP地址
- Java获取访问设备的ip地址,设备名称
- java 获取请求IP地址
- Java获取请求客户端的真实IP地址
- JAVA发送邮件和获取客户端真实ip地址
- java获取客户端真实IP地址
- 获取本机IP地址(java网络编程)
- java 获取网络ip地址
- 利用java获取当前时间
- java 获取用户客户端的IP地址
- 用Java来获取访问者真实的IP地址
- java 获取本地路由器分配给电脑的IP地址与主机名相关