1:场景描述
在做Netty相关项目的时侯linux查看磁盘空间,我们常常须要绑定本机的IP和端标语,假如我们把它写在配置文件中linux编程获取ip,这么我们每次换笔记本运行或则布署到其他环境时侯都须要更改配置文件。这样才会比较麻烦,假如我们把它弄成智能的获取本机的IP,这样我们的代码的可移植性就增强了。下边就介绍一种在windows和linux下边可以智能获取我们本机的局域网IP和内网IP的方式linux编程获取ip,不妥之处还请你们多多指教。
2:解决方式以及代码
首先贴上获取IP的工具类
<span class="hljs-javadoc">/** * Copyright (C) 2015 Raxtone * *<span class="hljs-javadoctag"> @className</span>:com.test.ip.IPUtils *<span class="hljs-javadoctag"> @description</span>:智能判断windows&linux平台获取外网ip和局域网ip工具类 * 注:window 获取外网IP是通过一个外部网站http://www.ip138.com/ip2city.asp * linux环境还需要额外的test.sh脚本(并且路径和本工具类一致) *<span class="hljs-javadoctag"> @version</span>:v1.0.0 *<span class="hljs-javadoctag"> @author</span>:yunqigao * * Modification History: * Date Author Version Description * ----------------------------------------------------------------- * 2015-3-28 yunqigao v1.0.0 create * * */</span> <span class="hljs-keyword">import</span> java.io.BufferedReader; <span class="hljs-keyword">import</span> java.io.IOException; <span class="hljs-keyword">import</span> java.io.InputStreamReader; <span class="hljs-keyword">import</span> java.io.LineNumberReader; <span class="hljs-keyword">import</span> java.net.InetAddress; <span class="hljs-keyword">import</span> java.net.URL; <span class="hljs-keyword">import</span> java.net.UnknownHostException; <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IPUtils</span> {</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String OS_NAME = <span class="hljs-keyword">null</span>; <span class="hljs-javadoc">/** * 查询本机外网IP网站 */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> String getWebIP = <span class="hljs-string">"http://www.ip138.com/ip2city.asp"</span>; <span class="hljs-javadoc">/** * 默认值 */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String IP = <span class="hljs-string">"未知"</span>; <span class="hljs-keyword">static</span> { System.out.println(<span class="hljs-string">"初始化获取系统名称..."</span>); OS_NAME = System.getProperty(<span class="hljs-string">"os.name"</span>); } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">getIP</span>(<span class="hljs-keyword">int</span> queryFlag) { <span class="hljs-keyword">if</span> (queryFlag == <span class="hljs-number">1</span>) { <span class="hljs-comment">// 查询外网IP</span> <span class="hljs-keyword">switch</span> (IPUtils.getOsType()) { <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>: IP = IPUtils.getWinOuterIP(); <span class="hljs-keyword">break</span>; <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>: IP = IPUtils.getLinuxIP(queryFlag); <span class="hljs-keyword">break</span>; <span class="hljs-keyword">default</span>: <span class="hljs-keyword">break</span>; } } <span class="hljs-keyword">else</span> { <span class="hljs-comment">// 查询内网IP</span> <span class="hljs-keyword">switch</span> (IPUtils.getOsType()) { <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>: IP = IPUtils.getWinInnerIP(); <span class="hljs-keyword">break</span>; <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>: IP = IPUtils.getLinuxIP(queryFlag); <span class="hljs-keyword">break</span>; <span class="hljs-keyword">default</span>: <span class="hljs-keyword">break</span>; } } <span class="hljs-keyword">return</span> IP; } <span class="hljs-javadoc">/** * 获取window平台下外网IP * *<span class="hljs-javadoctag"> @return</span> IP */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">getWinOuterIP</span>() { <span class="hljs-keyword">try</span> { URL url = <span class="hljs-keyword">new</span> URL(getWebIP); BufferedReader br = <span class="hljs-keyword">new</span> BufferedReader(<span class="hljs-keyword">new</span> InputStreamReader(url.openStream())); String s = <span class="hljs-string">""</span>; StringBuffer sb = <span class="hljs-keyword">new</span> StringBuffer(<span class="hljs-string">""</span>); String webContent = <span class="hljs-string">""</span>; <span class="hljs-keyword">while</span> ((s = br.readLine()) != <span class="hljs-keyword">null</span>) { <span class="hljs-comment">//System.err.println("---"+s);</span> sb.append(s + <span class="hljs-string">"rn"</span>); } br.close(); webContent = sb.toString(); <span class="hljs-keyword">int</span> start = webContent.indexOf(<span class="hljs-string">"["</span>) + <span class="hljs-number">1</span>; <span class="hljs-keyword">int</span> end = webContent.indexOf(<span class="hljs-string">"]"</span>); webContent = webContent.substring(start, end); <span class="hljs-keyword">return</span> webContent; } <span class="hljs-keyword">catch</span> (Exception e) { <span class="hljs-comment">//e.printStackTrace();</span> System.err.println(<span class="hljs-string">"获取外网IP网站访问失败!"</span>); <span class="hljs-keyword">return</span> IP; } } <span class="hljs-javadoc">/** * 获取window平台下内网IP * *<span class="hljs-javadoctag"> @return</span> IP */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">getWinInnerIP</span>() { InetAddress[] inetAdds; <span class="hljs-keyword">try</span> { inetAdds = InetAddress.getAllByName(InetAddress.getLocalHost() .getHostName()); } <span class="hljs-keyword">catch</span> (UnknownHostException e) { e.printStackTrace(); <span class="hljs-keyword">return</span> IP; } <span class="hljs-keyword">return</span> inetAdds[<span class="hljs-number">0</span>].getHostAddress(); } <span class="hljs-javadoc">/** * 获取linux下的IP *<span class="hljs-javadoctag"> @param</span> queryFlag * 1表示查询外网IP 2表示查询内网IP *<span class="hljs-javadoctag"> @return</span> IP *<span class="hljs-javadoctag"> @throws</span> IOException */</span> <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">getLinuxIP</span>(<span class="hljs-keyword">int</span> queryFlag) { LineNumberReader input = <span class="hljs-keyword">null</span>; String pathString = IPUtils.class.getResource(<span class="hljs-string">"/"</span>).getPath(); <span class="hljs-comment">//类的路径</span> <span class="hljs-comment">//System.out.println(pathString);</span> Process process=<span class="hljs-keyword">null</span>; String line = <span class="hljs-string">""</span>; <span class="hljs-keyword">try</span> { Runtime.getRuntime().exec(<span class="hljs-string">"dos2unix "</span>+pathString+<span class="hljs-string">"test.sh"</span>); process = Runtime.getRuntime().exec(<span class="hljs-string">"sh "</span>+pathString+<span class="hljs-string">"test.sh "</span>+(queryFlag==<span class="hljs-number">1</span>?<span class="hljs-string">"1"</span>:<span class="hljs-string">"2"</span>)); InputStreamReader ir = <span class="hljs-keyword">new</span> InputStreamReader(process.getInputStream()); input = <span class="hljs-keyword">new</span> LineNumberReader(ir); <span class="hljs-keyword">if</span>((line = input.readLine()) != <span class="hljs-keyword">null</span>) { IP = line; } } <span class="hljs-keyword">catch</span> (IOException e) { e.printStackTrace(); System.err.println(<span class="hljs-string">"linux下获取IP失败!"</span>); } <span class="hljs-comment">//System.out.println("exec shell result:ip====>" + IP);</span> <span class="hljs-keyword">return</span> IP; } <span class="hljs-javadoc">/** * 目前只支持window和linux两种平台 * *<span class="hljs-javadoctag"> @return</span> 1 window 2 linux -1:未知 */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getOsType</span>() { <span class="hljs-comment">// 将获取到的系统类型名称转为全部小写</span> OS_NAME = OS_NAME.toLowerCase(); <span class="hljs-keyword">if</span> (OS_NAME.startsWith(<span class="hljs-string">"win"</span>)) { <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>; } <span class="hljs-keyword">if</span> (OS_NAME.startsWith(<span class="hljs-string">"linux"</span>)) { <span class="hljs-keyword">return</span> <span class="hljs-number">2</span>; } <span class="hljs-keyword">return</span> -<span class="hljs-number">1</span>; } <span class="hljs-javadoc">/** * 测试方法 * *<span class="hljs-javadoctag"> @param</span> args *<span class="hljs-javadoctag"> @throws</span> IOException */</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span>(String[] args) <span class="hljs-keyword">throws</span> IOException { System.out.println(<span class="hljs-string">"操作系统为:"</span>+SystemOperate.fromCode(IPUtils.getOsType()+<span class="hljs-string">""</span>)); System.out.println(<span class="hljs-string">"内网IP为:"</span>+IPUtils.getIP(<span class="hljs-number">2</span>)); System.out.println(<span class="hljs-string">"外网IP为:"</span>+IPUtils.getIP(<span class="hljs-number">1</span>)); } }
下边是一个关于操作系统类型和名称的辅助枚举类
<span class="hljs-javadoc">/** * Copyright (C) 2015 Raxtone * * *<span class="hljs-javadoctag"> @className</span>:.SystemOperate *<span class="hljs-javadoctag"> @description</span>:TODO * *<span class="hljs-javadoctag"> @version</span>:v1.0.0 *<span class="hljs-javadoctag"> @author</span>:yunqigao * * Modification History: * Date Author Version Description * ----------------------------------------------------------------- * 2015-3-28 yunqigao v1.0.0 create * * */</span> <span class="hljs-keyword">import</span> java.util.Map; <span class="hljs-keyword">import</span> java.util.HashMap; <span class="hljs-javadoc">/** * 操作系统名称枚举 * 目前只有windows 和 linux系统 *<span class="hljs-javadoctag"> @author</span> Relieved * */</span> <span class="hljs-keyword">enum</span> SystemOperate{ WINDOWS(<span class="hljs-number">1</span>,<span class="hljs-string">"windows系统"</span>),LINUX(<span class="hljs-number">2</span>,<span class="hljs-string">"linux系统"</span>),UNKNOWN(<span class="hljs-number">3</span>,<span class="hljs-string">"未知系统"</span>); <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> operateType; <span class="hljs-keyword">private</span> String operateName; <span class="hljs-keyword">private</span> <span class="hljs-title">SystemOperate</span>(<span class="hljs-keyword">int</span> operateType, String operateName) { <span class="hljs-keyword">this</span>.operateType = operateType; <span class="hljs-keyword">this</span>.operateName = operateName; } <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getOperateType</span>() { <span class="hljs-keyword">return</span> operateType; } <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setOperateType</span>(<span class="hljs-keyword">int</span> operateType) { <span class="hljs-keyword">this</span>.operateType = operateType; } <span class="hljs-keyword">public</span> String <span class="hljs-title">getOperateName</span>() { <span class="hljs-keyword">return</span> operateName; } <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setOperateName</span>(String operateName) { <span class="hljs-keyword">this</span>.operateName = operateName; } <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> Map lookup = <span class="hljs-keyword">new</span> HashMap(); <span class="hljs-keyword">static</span> { <span class="hljs-keyword">for</span> (SystemOperate cp : values()) { lookup.put(cp.getOperateType()+<span class="hljs-string">""</span>, cp); } } <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title">fromCode</span>(String code) { <span class="hljs-keyword">return</span> lookup.get(code).operateName; } }
在windows系统下边直接执行工具类就可以看见右图获取到的IP
若果是在linux系统下我们还须要下边一个脚本test.sh
<span class="hljs-shebang">#!/bin/sh</span> <span class="hljs-comment">#Copyright (C) 2015 Raxtone</span> <span class="hljs-comment">#2015-3-28 </span> <span class="hljs-comment">#author:yunqigao </span> <span class="hljs-comment"># Get OS name</span> OS=`uname` IP=<span class="hljs-string">""</span> <span class="hljs-comment"># store IP</span> function <span class="hljs-function"><span class="hljs-title">getIp</span></span>(){ <span class="hljs-keyword">if</span> [ <span class="hljs-variable">$1</span> == <span class="hljs-string">"1"</span> ];<span class="hljs-keyword">then</span> <span class="hljs-comment">#echo "outer";</span> <span class="hljs-keyword">case</span> <span class="hljs-variable">$OS</span> <span class="hljs-keyword">in</span> Linux) IP=`curl ifconfig.me`;; <span class="hljs-comment">#FreeBSD|OpenBSD) IP=`ifconfig| grep -E 'inet.[0-9]' | grep -v '127.0.0.1' | awk '{ print $2}'` ;;</span> <span class="hljs-comment">#SunOS) IP=`ifconfig -a | grep inet | grep -v '127.0.0.1' | awk '{ print $2} '` ;;</span> *) IP=<span class="hljs-string">"Unknown"</span>;; <span class="hljs-keyword">esac</span> <span class="hljs-keyword">else</span> <span class="hljs-comment">#echo "inner";</span> <span class="hljs-keyword">case</span> <span class="hljs-variable">$OS</span> <span class="hljs-keyword">in</span> Linux) IP=`ifconfig| grep <span class="hljs-string">'inet addr:'</span>| grep -v <span class="hljs-string">'127.0.0.1'</span> | cut <span class="hljs-operator">-d</span>: <span class="hljs-operator">-f</span>2 | awk <span class="hljs-string">'{ print $1}'</span>`;; *) IP=<span class="hljs-string">"Unknown"</span>;; <span class="hljs-keyword">esac</span> <span class="hljs-keyword">fi</span> <span class="hljs-built_in">echo</span> <span class="hljs-string">"<span class="hljs-variable">$IP</span>"</span>; } getIp <span class="hljs-variable">$1</span>;
注:该脚本应当和工具类IPUtils置于同一目录下,不过你也可以自己定义linux 版本,自己更改路径就须要更改工具类IPUtils的getLinuxIP方式,将上面执行脚本的代码改成你脚本所在的目录即可
之后将编译后的.class文件和test.sh脚本一起拷贝到linux系统中,之后执行javaIPUtils,就可以见到如下信息!
在其他类中直接用下边的就可获取到本机的局域网和内网IP了
局域网IP为: IPUtils<span class="hljs-preprocessor">.getIP</span>(<span class="hljs-number">2</span>))<span class="hljs-comment">;</span> 外网IP为: IPUtils<span class="hljs-preprocessor">.getIP</span>(<span class="hljs-number">1</span>))<span class="hljs-comment">;</span>
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!