Java gets the local IP address

Source: Internet
Author: User
Tags nginx server

 1 public static void main (string[] args) {2 try {3 inetaddress address = Inetaddress.getlocalhos t ();//Gets the local IP address//pc-20140317pxkx/192.168.0.121 4 String hostaddress = address.gethostaddress ());//192.168. 0.121 5 InetAddress Address1 = Inetaddress.getbyname ("www.wodexiangce.cn");//Gets the IP address of the website, such as all of our              Requests are through Nginx, so here is actually the Nginx server IP Ground 6 String hostAddress1 = address1.gethostaddress ());//124.237.121.122 7              Inetaddress[] addresses = Inetaddress.getallbyname ("www.baidu.com");//returns all of its possible inetaddress objects based on hostname 8              for (InetAddress addr:addresses) {9 System.out.println (addr);//www.baidu.com/14.215.177.38 10 www.baidu.com/14.215.177.37 One} of catch (Unknownhostexception e) {E.printstack Trace (); +} 


/**
* Get server IP Address
* @return
*/
@SuppressWarnings ("Unchecked")
public static String Getserverip () {
String server_ip = null;
try {
Enumeration netinterfaces = Networkinterface.getnetworkinterfaces ();
inetaddress IP = null;
while (Netinterfaces.hasmoreelements ()) {
NetworkInterface ni = (networkinterface) netinterfaces.nextelement ();
ip = (inetaddress) ni.getinetaddresses (). Nextelement ();
Server_ip = Ip.gethostaddress ();
if (!ip.issitelocaladdress () &&!ip.isloopbackaddress ()
&& ip.gethostaddress (). IndexOf (":") = =-1) {
Server_ip = Ip.gethostaddress ();
Break
} else {
IP = null;
}
}
} catch (SocketException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

return server_ip;
}
}

Java gets the local IP address

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.