Java: Display Clients IP and port numbers

2019-06-03 23:45发布

Hello I've written a small UDP server program. I know the code to display the hosts IP is easy with the following code:

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

Is there a way of displaying the IP and port number of the Client who is connected to the server?

标签: java udp
2条回答
Viruses.
2楼-- · 2019-06-04 00:07

When you receive your UDP DatagramPacket you can retrieve the distant IP from where the packet originated by DatagramPacket.getAddress()

EDIT If you wish to get the 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楼-- · 2019-06-04 00:17

About that sample: String clientip = DatagramPacket.getAddress(); why don't you just cast it to String.

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

Though i don't really have a Java Compiler at the moment. but just try that. Will get back really soon.

查看更多
登录 后发表回答