devxlogo

Use ServerSocket to see who’s Calling your Server

Use ServerSocket to see who’s Calling your Server

You can use java.net.ServerSocket class to identify a remote machine that is accessing your server. A server socket waits for requests over a network. It then can perform operations based on the request, and can return a result to the machine initiating the request. Every socket connection accepted by your server will have information about the caller of your server. This information is encapsulated in an instance of java.net.InetAddress class.

The following demonstrates how to use ServerSocket to identify a remote machine calling your server:

 Socket aSocket = aServerSocket.accept();/*	aServerSocket is an instance of java.net.ServerSocket that you've	set up to wait for remote requests*/InetAddress inetAdd = aSocket.getInetAddress();String remoteIP = inetAdd.getHostAddress();String remoteHostname = inetAdd.getHostName();// you can also identify the port that channeled the request toaServerSocketString port = aSocket.getPort();System.out.println("Machine at IP: " + remoteIP + ", with hostname: " +remoteHostname + " called at port: + " port");

devx-admin

Share the Post: