|
支持Windows,Linux, 支持多网卡(根据网卡取本机配置的IP)
[li] /** [li] * 根据网卡取本机配置的IP [li] * 如果是双网卡的,则取出外网IP [li] * @return [li] */ [li] public static String getIp(){ [li] String localip=null;//本地IP,如果没有配置外网IP则返回它 [li] String netip=null;//外网IP [li] try { [li] Enumeration<NetworkInterface> netInterfaces =
NetworkInterface.getNetworkInterfaces(); [li] InetAddress ip = null; [li] boolean finded=false;//是否找到外网IP [li] while(netInterfaces.hasMoreElements() && !finded){ [li] NetworkInterface ni=netInterfaces.nextElement(); [li] Enumeration<InetAddress> address=ni.getInetAddresses(); [li] while(address.hasMoreElements()){ [li] ip=address.nextElement(); [li] System.out.println(ni.getName() +";"+ip.getHostAddress() +";ip.isSiteLocalAddress()="+ip.isSiteLocalAddress()+";ip.isLoopbackAddress()="+ip.isLoopbackAddress()); [li] if( !ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":")==-1){//外网IP [li] netip=ip.getHostAddress(); [li] finded=true; [li] break; [li] }else if(ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
&& ip.getHostAddress().indexOf(":")==-1){//内网IP [li] localip=ip.getHostAddress(); [li] } [li] } [li] } [li] } catch (SocketException e) { [li] e.printStackTrace(); [li] } [li] if(netip!=null && !"".equals(netip)){ [li] return netip; [li] }else{ [li] return localip; [li] } [li] } [/li] |
|