/**
* 局域网内获取指定IP下的NTP服务器时间
*/
private void getLocalNtpTime(MNtp localConfigNtp) {
String ntpServerIP = "局域网内的NTP服务器IP地址";
int ntpServerPort = 123; // NTP服务器默认端口号
try {
// 创建UDP Socket连接到NTP服务器
DatagramSocket socket = new DatagramSocket();
// 准备发送的数据
byte[] requestData = createNTPRequest();
// 创建UDP数据包,并指定NTP服务器的IP地址和端口号
InetAddress serverAddress = InetAddress.getByName(ntpServerIP);
DatagramPacket requestPacket = new DatagramPacket(requestData, requestData.length, serverAddress, ntpServerPort);
// 发送NTP请求
socket.send(requestPacket);
// 准备接收的数据
byte[] receiveBuffer = new byte[48];
DatagramPacket responsePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
// 接收NTP响应
socket.receive(responsePacket);
long ntpTime = parseNTPResponse(receiveBuffer);
// 处理时间信息
System.out.println("NTP服务器时间: " + ntpTime);
// 关闭Socket连接
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] createNTPRequest() {
// 构建NTP请求消息 byte[] request = new byte[48];
request[0] = 0x1B; // NTP协议版本号和操作码 // 其他字段省略,可参考NTP协议文档 return request;
}
private static long parseNTPResponse(byte[] response) {
// 解析NTP响应消息,提取时间信息 // 注意根据NTP协议的具体格式进行解析 long seconds = ((response[40] & 0xFFL) << 24) |
((response[41] & 0xFFL) << 16) |
((response[42] & 0xFFL) << 8) |
(response[43] & 0xFFL);
long fraction = ((response[44] & 0xFFL) << 24) |
((response[45] & 0xFFL) << 16) |
((response[46] & 0xFFL) << 8) |
(response[47] & 0xFFL);
return (seconds - 2208988800L) * 1000 + fraction * 1000 / 0x100000000L;
}