[Java] socket address InetAddress
Package com. sjf; import java.net. inet4Address; import java.net. inet6Address; import java.net. inetAddress; import java.net. networkInterface; import java.net. unknownHostException; import java. util. enumeration;/***** @ author sjf0115 **/public class InetAddressExample {public static void main (String [] args) {// Get the network interfaces and associated for this host try {NetworkInterface networkInterface = null; // obtain information about each interface of the host Enumeration
InterfaceList = NetworkInterface. getNetworkInterfaces (); if (interfaceList = null) {System. out. println ("-- No interfaces found --");} // if else {while (interfaceList. hasMoreElements () {networkInterface = interfaceList. nextElement (); // interface name System. out. println ("Interface->" + networkInterface. getName (); // obtain the address associated with the interface. The address may contain IPV4 or IPV6 address Enumeration according to different host configurations.
InetAddressList = networkInterface. getInetAddresses (); if (inetAddressList = null) {System. out. println ("-- No address for this NetworkInterface --");} // if else {InetAddress address = null; while (inetAddressList. hasMoreElements () {address = inetAddressList. nextElement (); // checks Each address to determine which IP address belongs to the subclass System. out. print (address instanceof Inet4Address? "(V4)": (address instanceof Inet6Address? "(V6 )":"(?) "); // Print the IP address System. out. println (":" + address. getHostAddress ();} // while} catch (Exception e) {} String host = "www.baidu.com "; try {// a name may be associated with multiple digital addresses this method returns a group of instances with all addresses associated with the given host name InetAddress [] addressesList = InetAddress. getAllByName (host); for (InetAddress address: addressesList) {System. out. println (address. getHostName () + "" + address. getHostAddress ();} // for // Determines the IP address of a host, given the host's name. inetAddress address2 = InetAddress. getByName (host); System. out. println (address2.getHostName () + "" + address2.getHostAddress (); // Returns the local host. inetAddress address3 = InetAddress. getLocalHost (); System. out. println (address3.getHostName () + "" + address3.getHostAddress ();} catch (UnknownHostException e) {e. printStackTrace ();}}}