How to get a domain name IP address with Java? The class that provides this feature is called java.net.inetaddress. We assume that there is such a domain name, which uses a static getByName to re-get an inetdress, then get the IP address that can be read. The following code is a very basic command line.
import java.net.InetAddress; import java.net.UnknownHostException; public class NsLookup {static public void main (String [] args) {try {InetAddress address = InetAddress.getByName (args [0]); System.out.println ( Args [0] ":" address.getdaddress ());} catch (unknownhostException UHE {system.err.println ("Unable to find:" args [0]);}}}
Inetaddress can also get IP addresses by using getaddress (), but its return value is an array of four bytes. Therefore, although getadDress () is useful in obtaining IP, it is not suitable for output.
The result of the output of the above command is like this:
Bash $ java code.nslookup www.sun.com www.sun.com: 192.18.97.241
Sometimes a domain name will contain more than one IP address, such as a Microsoft's web server, which is to keep the load balance. Inetaddress provides a way to get all IP addresses of a domain name. Let us consider the following code:
import java.net.InetAddress; import java.net.UnknownHostException; public class NsLookup {static public void main (String [] args) {try {String name = args [0]; InetAddress [] addresses = InetAddress.getAllByName (name) For (int i = 0; i Bash $ java code.nslookup www.sun.com www.sun.com [0]: 192.18.97.241 However, for www.microsoft.com, it will be output: Bash $ javad code / nslookup.java www.microsoft.com www.microsoft.com [0]: 207.46.197.101 www.microsoft.com [2]: 207.46.230.229 www .microsoft.com [3]: 207.46.197.113 www.microsoft.com [4]: 207.46.230.219 www.microsoft.com [5]: 207.46.230.220 www.microsoft.com [6]: 207.46.197.102 Due to INetAddress, LocalHost must have specially processed. If the string "localhost" directly enters the original version of the NSlookUP program, the following quite useless results: Bash $ java code.nslookup www.sun.com localhost: 127.0.0.1 We can manually look for local addresses: try {InetAddress localhost = InetAddress.getLocalHost (); System.out.println ( "localhost:" localhost.getHostAddress ()); System.out.println ( "localhost:" localhost.getHostName ());} catch ( UnknownHOSTEXCEPTION UHE {System.err.println ("Localhost Not Seeable. Something is ODD.");} This is an exemplified example: Localhost: 192.168.13.15 localhost: The domain name of the CRAB local host did not return a full machine domain name because it depends on the machine setting. Finally, inetaddress may be used to transform IP addresses to domain names of these addresses, which is useful for analyzing web logs. InetDress enables developers to deal with domain names, IP addresses, and allow them to interact with DNS servers.