Occasionally, you would like to know who is connecting to the server. You can use the InetAddress class to find the client's host name and IP address. The InetAddress class models an IP address. You can use the statement shown below to create an instance of InetAddress for the client on a socket:
InetAddress inetAddress = socket.getInetAddress();
Next, you can display the client's host name and IP address, as follows :
System.out.println( "Client's host name is " + inetAddress.getHostName()); System.out.println( "Client's IP Address is " + inetAddress.getHostAddress());
You can also create an instance of InetAddress from a host name or IP address using the static getByName method. For example, the following statement creates an InetAddress for the host liang.armstrong.edu :
InetAddress address = InetAddress.getByName( "liang.armstrong.edu" );
Listing 25.3 gives a program that identifies the host name and IP address of the arguments you pass in from the command line. Line 7 creates an InetAddress using the getByName method. Lines 8 “9 use the getHostName and getHostAddress methods to get the host name and IP address. Figure 25.6 shows a sample run of the program.
1 import java.net.*; 2 3 public class IdentifyHostNameIP { 4 public static void main(String[] args) { 5 for ( int i = ; i < args.length; i++) { 6 try { 7 InetAddress address = InetAddress.getByName(args[i]); 8 System.out.println( "Host name: " + address.getHostName() ); 9 System.out.println( "IP address: " + address.getHostAddress() ); 10 } 11 catch (UnknownHostException ex) { 12 System.err.println( "Unknown host or IP address " + args[i]); 13 } 14 } 15 } 16 } |