1

您好,我写了一个小型 UDP 服务器程序。我知道显示主机 IP 的代码很容易使用以下代码:

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

有没有办法显示连接到服务器的客户端的 IP 和端口号?

4

2 回答 2

3

当您收到 UDP 时DatagramPacket,您可以从数据包的来源处检索远程 IPDatagramPacket.getAddress()

编辑 如果您希望获取 IP 地址的字符串表示形式,只需使用DatagramPacket.getAddress().toString().

例子:

DatagramPacket p = new DatagramPacket(buffer, 
buffer.length); 
ds.receive(p);  // Receive data here... 
System.out.println("Received data packet from :"+p.getAddress().toString()); 
于 2012-07-06T21:48:49.550 回答
1

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.

于 2013-03-24T06:33:32.323 回答