java udp获取远程ip地址
时间: 2023-08-11 20:06:08 浏览: 142
以下是Java实现UDP获取远程IP地址的示例代码:
```java
import java.net.*;
public class UdpRemoteAddress {
public static void main(String[] args) throws Exception {
// 创建UDP Socket
DatagramSocket socket = new DatagramSocket();
// 发送UDP消息
String message = "Hello, world!";
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 9999;
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.length(), address, port);
socket.send(packet);
// 接收UDP消息
byte[] buffer = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(buffer, buffer.length);
socket.receive(receivePacket);
// 获取远程IP地址
InetAddress remoteAddress = receivePacket.getAddress();
int remotePort = receivePacket.getPort();
System.out.println("Remote address: " + remoteAddress.getHostAddress() + ", port: " + remotePort);
// 关闭UDP Socket
socket.close();
}
}
```
在上述代码中,首先创建了一个UDP Socket,并发送一条UDP消息到指定的IP地址和端口号,然后接收UDP消息,并通过`getAddress()`方法获取远程IP地址和端口号,最后输出远程IP地址和端口号,并关闭UDP Socket。
阅读全文