Java获取本机公网ip
2016-06-27 14:07
417 查看
import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; /** * * @anthor leo * @date 2016年6月27日下午12:40:14 * @description * **/ public class Main { public static void main(String[] args) throws SocketException { System.out.println(Main.getRealIp()); } public static String getRealIp() throws SocketException { String localip = null;// 本地IP,如果没有配置外网IP则返回它 String netip = null;// 外网IP Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; boolean finded = false;// 是否找到外网IP while (netInterfaces.hasMoreElements() && !finded) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> address = ni.getInetAddresses(); while (address.hasMoreElements()) { ip = address.nextElement(); if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP netip = ip.getHostAddress(); finded = true; break; } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 内网IP localip = ip.getHostAddress(); } } } if (netip != null && !"".equals(netip)) { return netip; } else { return localip; } } }
相关文章推荐
- spring mvc 条件查询导出excel
- Java核心API列表
- java list去重
- java框架之springmvc02(自定义配置文件位置)
- Java中HttpServletResponse响应中文出现乱码问题
- 31. Next Permutation (java 字典序生成下一个排列)
- Spring基础学习三 : 依赖注入
- Spring <context:annotation-config/> 存在的含义
- Spring jdbctemplate IN 的使用
- Java基础知识:异常
- 在Windows上面安装NDK,Eclipse上配置NDK
- Eclipse在线安装fatjar插件
- Ubuntu中配置Java环境变量时,出现command not found问题解决记录
- Java 类的热替换 —— 概念、设计与实现
- Eclipse中安装genymotion插件
- Spring MVC Captcha 验证码 (附Servlet实现方式)
- mysql/Java服务端对emoji的支持
- Spring事务管理
- JSON中,java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher问题解决
- 【java多线程系列】java中的volatile的内存语义