Java: mapping IP clients and port numbers

Hello, I wrote a small UDP server program. I know that the code to display host IP addresses is easy with the following code:

System.out.println("Listening Port: " + serverSocket.getLocalPort());
System.out.println("IP: " + myIp.getHostAddress());

Is there a way to display the IP number and port of the client that is connected to the server?

+1
source share
2 answers

When you receive your UDP DatagramPacket, you can get the remote IP address from where the packet was sentDatagramPacket.getAddress()

EDIT If you want a string representation of the IP address, just use DatagramPacket.getAddress().toString().

Example:

DatagramPacket p = new DatagramPacket(buffer, 
buffer.length); 
ds.receive(p);  // Receive data here... 
System.out.println("Received data packet from :"+p.getAddress().toString()); 
+3
source

About this sample: String clientip = DatagramPacket.getAddress(); why don't you just translate it on String.

String clientip = (String) DatagramPacket.getAddress();

Java-. . .

+1

All Articles