Home> System Tutorial> LINUX> body text

Intelligent method of obtaining local IP in Netty project to improve code portability

王林
Release: 2024-07-25 07:46:53
Original
643 people have browsed it

Netty 项目中智能获取本机 IP 的方法,提高代码可移植性

1:场景描述

在做Netty相关项目的时侯linux查看磁盘空间,我们常常须要绑定本机的IP和端标语,假如我们把它写在配置文件中linux编程获取ip,这么我们每次换笔记本运行或则布署到其他环境时侯都须要更改配置文件。这样才会比较麻烦,假如我们把它弄成智能的获取本机的IP,这样我们的代码的可移植性就增强了。下边就介绍一种在windows和linux下边可以智能获取我们本机的局域网IP和内网IP的方式linux编程获取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 + "rn"); } 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)); } }
Copy after login

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

/** * 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 lookup = new HashMap(); static { for (SystemOperate cp : values()) { lookup.put(cp.getOperateType()+"", cp); } } public static String fromCode(String code) { return lookup.get(code).operateName; } }
Copy after login

在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;
Copy after login

注:该脚本应当和工具类IPUtils置于同一目录下,不过你也可以自己定义linux 版本,自己更改路径就须要更改工具类IPUtils的getLinuxIP方式,将上面执行脚本的代码改成你脚本所在的目录即可

之后将编译后的.class文件和test.sh脚本一起拷贝到linux系统中,之后执行javaIPUtils,就可以见到如下信息!

在其他类中直接用下边的就可获取到本机的局域网和内网IP了

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

The above is the detailed content of Intelligent method of obtaining local IP in Netty project to improve code portability. For more information, please follow other related articles on the PHP Chinese website!

source:itcool.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!