How to obtain native intranet and extranet IP (windows+linux)

Source: Internet
Author: User
Tags get ip shebang

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

First, attach the tool class for IP

/** * Copyright (C) raxtone * * @className: com.test.ip.IPUtils * @description: Smart judgment windows &linux platform get extranet IP and LAN IP tool class * Note: Window acquisition of an extranet IP is through an external Web site http://www.ip138.com/ip2city.asp * Linux environment also requires additional test.sh scripts ( And the path is consistent with this tool class) * @version: v1.0.0 * @author: Yunqigao * * Modification History: * Date author version Descri ption *-----------------------------------------------------------------* 2015-3-28 Yunqigao v1.0.0 Create * * * *ImportJava.io.BufferedReader;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.LineNumberReader;Importjava.net.InetAddress;ImportJava.net.URL;ImportJava.net.UnknownHostException; Public  class iputils {    Private StaticString Os_name =NULL;/** * Query the local network IP site * *    Private Static FinalString Getwebip ="Http://www.ip138.com/ip2city.asp";/** * Default value * /    Private StaticString IP ="Unknown";Static{System.out.println ("Initialize get system name ..."); Os_name = System.getproperty ("Os.name"); } Public StaticStringGetIP(intQueryflag) {if(Queryflag = =1) {//Query extranet IP            Switch(Iputils.getostype ()) { Case 1: IP = Iputils.getwinouterip (); Break; Case 2: IP = Iputils.getlinuxip (Queryflag); Break;default: Break; }        }Else{//Query Intranet IP            Switch(Iputils.getostype ()) { Case 1: IP = Iputils.getwininnerip (); Break; Case 2: IP = Iputils.getlinuxip (Queryflag); Break;default: Break; }        }returnIP; }/** * Get the window platform extranet IP * * @return IP */    Private StaticStringGetwinouterip() {Try{URL url =NewURL (GETWEBIP); BufferedReader br =NewBufferedReader (NewInputStreamReader (Url.openstream ())); String s =""; StringBuffer SB =NewStringBuffer (""); String webcontent =""; while((s = br.readline ())! =NULL) {//system.err.println ("---" +s);Sb.append (S +"\ r \ n");            } br.close (); WebContent = Sb.tostring ();intStart = Webcontent.indexof ("[") +1;intEnd = Webcontent.indexof ("]"); WebContent = webcontent.substring (start, end);returnWebContent; }Catch(Exception e) {//e.printstacktrace ();System.err.println ("Getting access to extranet IP sites failed!" ");returnIP; }    }/** * Get Intranet IP * * @return IP * * under Window platform * *    Private StaticStringGetwininnerip() {inetaddress[] inetadds;Try{Inetadds = Inetaddress.getallbyname (Inetaddress.getlocalhost (). GetHostName ()); }Catch(Unknownhostexception e) {E.printstacktrace ();returnIP; }returninetadds[0].gethostaddress (); }/** * Get the IP under Linux * @param Queryflag * 1 indicates that querying an extranet IP 2 means querying the intranet IP * @return IP * @t Hrows IOException * /    Private StaticStringGetlinuxip(intQueryflag) {LineNumberReader input =NULL; String pathstring = IPUtils.class.getResource ("/"). GetPath ();//The path of the class         //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 =NewInputStreamReader (Process.getinputstream ()); input =NewLineNumberReader (IR);if(line = Input.readline ())! =NULL) {IP = line; }         }Catch(IOException e)            {E.printstacktrace (); System.err.println ("Failed to get IP under Linux!"); }//system.out.println ("exec shell result:ip====>" + IP);        returnIP; }/** * Currently only supports Windows and Linux two platforms * * @return 1 window 2 linux-1: Unknown */     Public Static int Getostype() {//Convert the acquired system type name to all lowercaseOs_name = Os_name.tolowercase ();if(Os_name.startswith ("Win")) {return 1; }if(Os_name.startswith ("Linux")) {return 2; }return-1; }/** * Test method * * @param args * @throws ioexception */     Public Static void Main(string[] args)throwsIOException {System.out.println ("The operating system is:"+systemoperate.fromcode (Iputils.getostype () +"")); System.out.println ("Intranet IP is:"+iputils.getip (2)); System.out.println ("External network IP:"+iputils.getip (1)); }}

The following is a secondary enumeration class about the operating system type and name

/** * Copyright (C) raxtone * * * @className:. Systemoperate * @description: TODO * * @version: v1.0.0 * @author: Yunqigao * * Modification Hist Ory: * Date Author Version Description *-----------------------------------------------------------------* 2015-3-28 Yunqigao v1.0.0 Create * * * * *ImportJava.util.Map;ImportJava.util.HashMap;/** * Operating System name enumeration * Currently only Windows and Linux systems * @author relieved * */enumsystemoperate{WINDOWS (1,"Windows System"), LINUX (2,"Linux system"), UNKNOWN (3,"Unknown System");Private intOperatetype;PrivateString Operatename;Private systemoperate(intOperatetype, String operatename) { This. Operatetype = Operatetype; This. operatename = Operatename; } Public int Getoperatetype() {returnOperatetype; } Public void Setoperatetype(intOperatetype) { This. Operatetype = Operatetype; } PublicStringGetoperatename() {returnOperatename; } Public void Setoperatename(String operatename) { This. operatename = Operatename; }Private Static Finalmap<string, systemoperate> lookup =NewHashmap<string, systemoperate> ();Static{ for(Systemoperate cp:values ()) {Lookup.put (Cp.getoperatetype () +"", CP); }    } Public StaticStringFromcode(String code) {returnLookup.get (code). Operatename; }}

You can see the IP you get by executing the tool class directly below the Windows system

If it is under a Linux system we need the following script test.sh

#!/bin/sh#Copyright (C) Raxtone#2015 -3-28#author: Yunqigao# Get OS nameos= ' uname ' ip=""# Store IPfunctionGetIP(){if[ $=="1"]; Then#echo "outer";     Case $OS inchLinux) ip= ' Curl ifconfig.me ';;#FreeBSD | OpenBSD) ip= ' ifconfig | Grep-e ' inet. [0-9] ' | Grep-v ' 127.0.0.1 ' | awk ' {print $} ';;        #SunOS) ip= ' Ifconfig-a | grep inet | Grep-v ' 127.0.0.1 ' | awk ' {print $} ';;*) ip="Unknown";;EsacElse#echo "inner";     Case $OS inchLinux) ip= ' ifconfig | Grep' inet addr: '| Grep-v' 127.0.0.1 '| Cut- D:- F2 | Awk' {print '} '`;; *) ip="Unknown";;EsacfiEcho "$IP";} GetIP $;

Note: The script should be in the same directory as the tool class Iputils, but you can also define your own, modify the path you need to modify the tool class Iputils Getlinuxip method, the script inside the code to the directory where you can
Then copy the compiled. class file and the test.sh script to the Linux system, then execute the Java iputils, and you can see the following information!

In other classes directly with the following can be obtained to the native local area network and the network IP

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

How to obtain native intranet and extranet IP (windows+linux)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.