In network programming, in order to access a host, we must know its IP address. In Java, the operation of acquiring an IP address is encapsulated into a class--inetaddress, which makes it easy to obtain an IP.
Here's how to take advantage of this class method to get the IP of the local host
Import Java.net.*;class Ipdemo {public static void main (string[] args) throws unknownhostexception{inetaddress ina = Ineta Ddress.getlocalhost (); System.out.println (Ina.tostring ());}}
The class has no constructor method and can only get the instance object of the class through static method Getlocalhost, and must declare the unknownhostexception exception when acquiring the host. The results are as follows:
If you want to print the host name and host address separately, as follows:
Import Java.net.*;class Ipdemo {public static void main (string[] args) throws unknownhostexception{inetaddress ina = Ineta Ddress.getlocalhost (); String name = Ina.gethostname (); String addr = ina.gethostaddress (); System.out.println (Ina.tostring ()); SYSTEM.OUT.PRINTLN (name); System.out.println (addr);}}
Through the instance method GetHostName and gethostaddress can obtain the host name and the host address respectively, the result is as follows:
This is to get the local host, then if you want to get a non-local host what to do, continue to see it!
Import Java.net.*;class Ipdemo {public static void main (string[] args) throws unknownhostexception{inetaddress ina = Ineta Ddress.getbyname ("www.baidu.com");//can also be used directly with ip:180.97.33.107string name = Ina.gethostname (); String addr = ina.gethostaddress (); System.out.println (Ina.tostring ()); SYSTEM.OUT.PRINTLN (name); System.out.println (addr);}}
Can see, just take advantage of the Getbyname method, the rest is the same, the method has a parameter, the parameter is the specified host IP or domain name, the result is as follows:
Of course, Baidu's IP should be more than one, want to get all, what should be done?
Import Java.net.*;class Ipdemo {public static void main (string[] args) throws unknownhostexception{inetaddress[] Inas = in Etaddress.getallbyname ("www.baidu.com"); for (int i = 0; i < inas.length; i++) {System.out.println (inas[i].tostring () );}}}
Look at the results:
Similarly, there are:
Java Network Programming--Get IP