码迷,mamicode.com
首页 > Windows程序 > 详细

如何获取本机内网和外网IP(windows+linux)

时间:2015-03-28 17:23:20      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:获取ip   本机ip   工具类   linux   windows   

1:场景描述

 在做Netty相关项目的时候,我们往往需要绑定本机的IP和端口号,如果我们把它写在配置文件中,那么我们每次换电脑运行或者部署到其他环境时候都需要修改配置文件。这样就会比较麻烦,如果我们把它做成智能的获取本机的IP,这样我们的代码的可移植性就提高了。下面就介绍一种在windows和linux下面可以智能获取我们本机的局域网IP和外网IP的方法,不妥之处还请大家多多指教。

2:解决方法以及代码

首先贴上获取IP的工具类

/**
 * Copyright (C) 2015 Raxtone
 *
 * @className:com.test.ip.IPUtils
 * @description:智能判断windows&linux平台获取外网ip和局域网ip工具类
 * 注:window 获取外网IP是通过一个外部网站http://www.ip138.com/ip2city.asp
 * linux环境还需要额外的test.sh脚本(并且路径和本工具类一致)
 * @version:v1.0.0
 * @author:yunqigao
 *
 * Modification History:
 * Date Author Version Description
 * -----------------------------------------------------------------
 * 2015-3-28 yunqigao v1.0.0 create
 *
 *
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;


public class IPUtils {
    private static String OS_NAME = null;
    /**
     * 查询本机外网IP网站
     */
    private static final String getWebIP = "http://www.ip138.com/ip2city.asp";
    /**
     * 默认值
     */
    private static String IP = "未知";
    static {
        System.out.println("初始化获取系统名称...");
        OS_NAME = System.getProperty("os.name");
    }

    public static String getIP(int queryFlag) {
        if (queryFlag == 1) {
            // 查询外网IP
            switch (IPUtils.getOsType()) {
            case 1:
                IP = IPUtils.getWinOuterIP();
                break;
            case 2:
                IP = IPUtils.getLinuxIP(queryFlag);
                break;
            default:
                break;
            }
        } else {
            // 查询内网IP
            switch (IPUtils.getOsType()) {
            case 1:
                IP = IPUtils.getWinInnerIP();
                break;
            case 2:
                IP = IPUtils.getLinuxIP(queryFlag);
                break;
            default:
                break;
            }
        }

        return IP;
    }

    /**
     * 获取window平台下外网IP
     * 
     * @return IP
     */
    private static String getWinOuterIP() {
        try {
            URL url = new URL(getWebIP);
            BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
            String s = "";
            StringBuffer sb = new StringBuffer("");
            String webContent = "";
            while ((s = br.readLine()) != null) {
                //System.err.println("---"+s);
                sb.append(s + "\r\n");
            }
            br.close();
            webContent = sb.toString();
            int start = webContent.indexOf("[") + 1;
            int end = webContent.indexOf("]");
            webContent = webContent.substring(start, end);
            return webContent;
        } catch (Exception e) {
            //e.printStackTrace();
            System.err.println("获取外网IP网站访问失败!");
            return IP;
        }

    }

    /**
     * 获取window平台下内网IP
     * 
     * @return IP
     */
    private static String getWinInnerIP() {
        InetAddress[] inetAdds;
        try {
            inetAdds = InetAddress.getAllByName(InetAddress.getLocalHost()
                    .getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return IP;
        }
        return inetAdds[0].getHostAddress();
    }

    /**
     * 获取linux下的IP
     * @param queryFlag
     * 1表示查询外网IP 2表示查询内网IP
     * @return IP
     * @throws IOException 
     */
    private static String getLinuxIP(int queryFlag) {
         LineNumberReader input = null;
         String pathString = IPUtils.class.getResource("/").getPath();
         //类的路径
         //System.out.println(pathString);
         Process process=null;
         String line = "";
         try {
            Runtime.getRuntime().exec("dos2unix "+pathString+"test.sh");
            process = Runtime.getRuntime().exec("sh "+pathString+"test.sh "+(queryFlag==1?"1":"2"));
            InputStreamReader ir = new InputStreamReader(process.getInputStream());
            input = new LineNumberReader(ir);
            if((line = input.readLine()) != null) {
                IP = line;
            }
         } catch (IOException e) {
            e.printStackTrace();
            System.err.println("linux下获取IP失败!");
        }
        //System.out.println("exec shell result:ip====>" + IP);
        return IP;
    }
    /**
     * 目前只支持window和linux两种平台
     * 
     * @return 1 window 2 linux -1:未知
     */
    public static int getOsType() {
        // 将获取到的系统类型名称转为全部小写
        OS_NAME = OS_NAME.toLowerCase();
        if (OS_NAME.startsWith("win")) {
            return 1;
        }
        if (OS_NAME.startsWith("linux")) {
            return 2;
        }
        return -1;
    }

    /**
     * 测试方法
     * 
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        System.out.println("操作系统为:"+SystemOperate.fromCode(IPUtils.getOsType()+""));
        System.out.println("内网IP为:"+IPUtils.getIP(2));
        System.out.println("外网IP为:"+IPUtils.getIP(1));
    }
}

下面是一个关于操作系统类型和名称的辅助枚举类


/**
 * Copyright (C) 2015 Raxtone
 *
 *
 * @className:.SystemOperate
 * @description:TODO
 *
 * @version:v1.0.0
 * @author:yunqigao
 *
 * Modification History:
 * Date Author Version Description
 * -----------------------------------------------------------------
 * 2015-3-28 yunqigao v1.0.0 create
 *
 *
 */
import java.util.Map;
import java.util.HashMap;
/**
 * 操作系统名称枚举
 * 目前只有windows 和 linux系统
 * @author Relieved
 *
 */
enum SystemOperate{
    WINDOWS(1,"windows系统"),LINUX(2,"linux系统"),UNKNOWN(3,"未知系统");

    private int operateType;
    private String operateName;

    private SystemOperate(int operateType, String operateName) {
        this.operateType = operateType;
        this.operateName = operateName;
    }
    public int getOperateType() {
        return operateType;
    }
    public void setOperateType(int operateType) {
        this.operateType = operateType;
    }
    public String getOperateName() {
        return operateName;
    }
    public void setOperateName(String operateName) {
        this.operateName = operateName;
    }
    private static final Map<String, SystemOperate> lookup = new HashMap<String, SystemOperate>();
    static {
        for (SystemOperate cp : values()) {
            lookup.put(cp.getOperateType()+"", cp);
        }
    }
    public static String fromCode(String code) {
        return lookup.get(code).operateName;
    }
}

在windows系统下面直接执行工具类就可以看到下图获取到的IP
技术分享
如果是在linux系统下我们还需要下面一个脚本test.sh

#!/bin/sh
#Copyright (C) 2015 Raxtone
#2015-3-28 
#author:yunqigao 
# Get OS name
    OS=`uname`
    IP=""
# store IP
function getIp(){
if [ $1 == "1" ];then
#echo "outer";
    case $OS in
        Linux) IP=`curl ifconfig.me`;;
        #FreeBSD|OpenBSD) IP=`ifconfig  | grep -E ‘inet.[0-9]‘ | grep -v ‘127.0.0.1‘ | awk ‘{ print $2}‘` ;;
        #SunOS) IP=`ifconfig -a | grep inet | grep -v ‘127.0.0.1‘ | awk ‘{ print $2} ‘` ;;
        *) IP="Unknown";;
    esac
else
#echo "inner";
    case $OS in
        Linux) IP=`ifconfig  | grep ‘inet addr:‘| grep -v ‘127.0.0.1‘ | cut -d: -f2 | awk ‘{ print $1}‘`;;
        *) IP="Unknown";;
    esac
fi
echo "$IP";
}
getIp $1;

注:该脚本应该和工具类IPUtils放在同一目录下,不过你也可以自己定义,自己修改路径就需要修改工具类IPUtils的getLinuxIP方法,将里面执行脚本的代码改成你脚本所在的目录即可
然后将编译后的.class文件和test.sh脚本一起拷贝到linux系统中,然后执行java IPUtils,就可以看到如下信息!
技术分享
在其他类中直接用下面的就可获取到本机的局域网和外网IP了

局域网IP为:
IPUtils.getIP(2));
外网IP为:
IPUtils.getIP(1));

如何获取本机内网和外网IP(windows+linux)

标签:获取ip   本机ip   工具类   linux   windows   

原文地址:http://blog.csdn.net/gao36951/article/details/44702323

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