加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

Java 如何获取机器的外网IP

(2018-03-07 11:40:33)
标签:

网卡

云主机

网络连接

ip

分类: 软件开发
public class MyTest {

    public static void main(String[] args) throws Exception {
        System.out.print(getLocalIp());
    }

    private static String getLocalIp() {
        try {
            Enumeration networks = NetworkInterface.getNetworkInterfaces();
            while (networks.hasMoreElements()) {
                Enumeration addrs = networks.nextElement().getInetAddresses();
                while (addrs.hasMoreElements()) {
                    InetAddress ip = addrs.nextElement();
                    if (ip instanceof Inet4Address && !ip.isSiteLocalAddress() && !ip.isLoopbackAddress()) {
                        // 从网卡获取外网IP
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

        try {
            // 外网IP不存在,那么获取内网IP
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return "";
    }
}

    java文件变成.class 文件后,上传到服务器。执行 java MyTest 命令即可。

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有