The inetaddress is used to represent an IP address. An Inetadress object represents an IP address,
- Getbyname (String host): Determines the IP address of the host, given the host name, which can be a machine name (such as "
java.sun.com ") or a textual representation of its IP address. If a literal IP address is provided, only the validity of the address format is checked
- GetHostName (): Gets the host name of this IP address
- Gethostaddress (): Returns the IP address string (in textual representation)
- Getlocalhost (): Returns the local host
Getting the InetAddress object
The InetAddress constructor is not public, so it needs to be obtained by the static method it provides:
- Static inetaddress[] Getallbyname (String host)
- Static InetAddress getbyaddress (byte[] addr)
- Static InetAddress getbyaddress (String host,byte[] addr)
- Static InetAddress Getbyname (String host)
- Static InetAddress Getlocalhost ()
Note: In these static methods, the most common should be the Getbyname (String host) method, only need to pass in the name of the target host, InetAddress will try to connect to the DNS server, and get the operation of the IP address
Packagecom.yyx.test;Importjava.net.InetAddress; Public classtestinetaddress { Public Static voidMain (string[] args) {inetaddress inetaddress=NULL; InetAddress iaddress=NULL; Try{inetaddress= Inetaddress.getbyname ("www.baidu.com"); System.out.println (inetaddress); System.out.println (Inetaddress.gethostaddress ()); System.out.println (Inetaddress.gethostname ()); System.out.println ("============================="); Iaddress=Inetaddress.getlocalhost (); System.out.println (iaddress); System.out.println (Iaddress.gethostaddress ()); System.out.println (Iaddress.gethostname ()); } Catch(Exception e) {e.printstacktrace (); } }}
Operation Result:
www.baidu.com/61.135.169.125
61.135.169.125
Www.baidu.com
=============================
desktop-f4p6spk/192.168.1.107
192.168.1.107
Desktop-f4p6spk
Java Network Programming InetAddress class