About Java getting the local server IP issues

Source: Internet
Author: User
Tags get ip

Java gets the local server IP, our simplest notation:

Import java.net.InetAddress;  public class catchip{public static void Main (string[] args)    {        try        {            //Get IP address            String IP = inetaddres S.getlocalhost (). gethostaddress ();                   SYSTEM.OUT.PRINTLN ("IP address:" +IP);        }        catch (Exception e)        {            System.out.println ("exception:" + E);            E.printstacktrace ();}}}    

But there's a problem with that we're in the Windows system and we can get the right IP

But on Linux, the IP address that may be obtained is: 127.0.0.1

And in the production system, a server may have a number of network cards, so that the IP is more troublesome, specifically to understand the production system server IP address we can refer to this URL:

Http://blog.163.com/[email protected]/blog/static/3259410020117493943770/?suggestedreading

The

Code is as follows:

/* To change this template, choose Tools | Templates * and open the template in the editor. */package org.lib.com;/** * * @author Administrator */import java.io.bufferedreader;import java.io.ioexception;import Java.io.inputstreamreader;import Java.net.inet6address;import Java.net.inetaddress;import Java.net.networkinterface;import Java.net.socketexception;import Java.net.unknownhostexception;import     Java.util.arraylist;import Java.util.enumeration;import java.util.List;        public class Testaddr {/** * get native all IP */private static string[] Getalllocalhostip () {        list<string> res = new arraylist<string> ();        Enumeration netinterfaces;            try {netinterfaces = networkinterface.getnetworkinterfaces ();            inetaddress IP = null;                        while (Netinterfaces.hasmoreelements ()) {NetworkInterface ni = (networkinterface) netinterfaces                . Nextelement (); System.out.pRINTLN ("---Name---:" + ni.getname ());                Enumeration nii = Ni.getinetaddresses ();                    while (Nii.hasmoreelements ()) {IP = (inetaddress) nii.nextelement ();                        if (Ip.gethostaddress (). IndexOf (":") = =-1) {Res.add (ip.gethostaddress ());                    System.out.println ("ip= of this Machine" + ip.gethostaddress ());            }}}} catch (SocketException e) {e.printstacktrace ();        } return (string[]) Res.toarray (new string[0]);           } public static string Getlocalip () {String ip = "";                   try {enumeration<?> e1 = (enumeration<?>) networkinterface.getnetworkinterfaces ();                         while (E1.hasmoreelements ()) {NetworkInterface ni = (networkinterface) e1.nextelement (); System.out.println ("Getlocalip--nic.getdisplayname ():" + Ni.getdisPlayname ());                       System.out.println ("Getlocalip--nic.getname ():" + ni.getname ());                       if (!ni.getname (). Equals ("eth0")) {continue;                           } else {enumeration<?> e2 = ni.getinetaddresses ();                           while (E2.hasmoreelements ()) {inetaddress ia = (inetaddress) e2.nextelement ();                           if (IA instanceof inet6address) continue;                       ip = ia.gethostaddress ();                       } break;                   }}} catch (SocketException e) {e.printstacktrace ();               System.exit (-1);           } return IP;                 } public static string Getwinlocalip () {String ip = "";                    try { Enumeration <?> e1 = (enumeration <?>) networkinterface.getnetworkinterfaces (); while (E1.hasmoreelements ()) {NetworkInterface ni = (networkinterface) e1.ne                        Xtelement ();                         System.out.println ("Getwinlocalip--nic.getdisplayname ():" + ni.getdisplayname ());                        System.out.println ("Getwinlocalip--nic.getname ():" + ni.getname ());                         Enumeration <?> e2 = Ni.getinetaddresses (); while (E2.hasmoreelements ()) {inetaddress ia = (inetaddress) e2.next                             Element ();                     ip = ia.gethostaddress ();                     }}} catch (SocketException e) {                 E.printstacktrace ();                 System.exit (-1);             } return IP;    }    /** * Get native all Physical Address * * @return */public static String getmacaddress () {S        Tring mac = "";         String line = "";       String OS = System.getproperty ("Os.name"); if (OS! = null && os.startswith ("Windows")) {try {String command = "cmd.exe/c IPC                    Onfig/all ";                         Process p = runtime.getruntime (). exec (command);                         BufferedReader br = new BufferedReader (new InputStreamReader (p. getInputStream ()));  while (line = Br.readline ()) = null) {if (Line.indexof ("Physical Address") > 0)                                 {int index = Line.indexof (":") + 2;                                 Mac = line.substring (index);                        Break                     }} br.close ();  } catch (IOException e) {}          } return Mac;            } public string Getmacaddress (string host) {string mac = "";                 StringBuffer sb = new StringBuffer (); try {networkinterface ni = networkinterface.getbyinetaddress (inetaddress. getbyname                     (host));                     byte[] Macs = ni.gethardwareaddress ();                for (int i = 0; i < macs.length; i++) {//Mac = Integer.tohexstring (Macs[i] & 0xFF);                if (mac.length () = = 1) {//Mac = ' 0 ' + mac;                }////Sb.append (Mac + "-");            }} catch (SocketException e) {e.printstacktrace ();            } catch (Unknownhostexception e) {e.printstacktrace ();            } mac = Sb.tostring ();                 Mac = mac.substring (0, Mac.length ()-1); ReTurn Mac; }/** * @param args */public static void main (string[] args) {Testaddr.get            Alllocalhostip ();            System.out.println ("Localip:" +testaddr.getlocalip ());            System.out.println ("Getwinlocalip:" +testaddr.getwinlocalip ());        System.out.println (Testaddr.getmacaddress ()); }         }
Of course, we often have a lazy approach, that is to get the server hostname, that is, the hostname, the wording is more unified simple:

Import java.net.InetAddress;  public class catchhostname{public static void Main (string[] args)    {        try        {            //Get computer name            String name = in Etaddress.getlocalhost (). GetHostName ();            SYSTEM.OUT.PRINTLN ("Computer name:" +name);                 }        catch (Exception e)        {            System.out.println ("exception:" + E);            E.printstacktrace ();}}}    


About Java getting the local server IP issues

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.