/**
? ? * 局域網(wǎng)內(nèi)獲取指定IP下的NTP服務(wù)器時(shí)間
? ? */
? ? private void getLocalNtpTime(MNtp localConfigNtp) {
? ? String ntpServerIP = "局域網(wǎng)內(nèi)的NTP服務(wù)器IP地址";
? ? ? ? int ntpServerPort = 123; // NTP服務(wù)器默認(rèn)端口號(hào)
? ? ? ? try {
? ? ? ? ? ? // 創(chuàng)建UDP Socket連接到NTP服務(wù)器
? ? ? ? ? ? DatagramSocket socket = new DatagramSocket();
? ? ? ? ? ? // 準(zhǔn)備發(fā)送的數(shù)據(jù)
? ? ? ? ? ? byte[] requestData = createNTPRequest();
? ? ? ? ? ? // 創(chuàng)建UDP數(shù)據(jù)包译仗,并指定NTP服務(wù)器的IP地址和端口號(hào)
? ? ? ? ? ? InetAddress serverAddress = InetAddress.getByName(ntpServerIP);
? ? ? ? ? ? DatagramPacket requestPacket = new DatagramPacket(requestData, requestData.length, serverAddress, ntpServerPort);
? ? ? ? ? ? // 發(fā)送NTP請(qǐng)求
? ? ? ? ? ? socket.send(requestPacket);
? ? ? ? ? ? // 準(zhǔn)備接收的數(shù)據(jù)
? ? ? ? ? ? byte[] receiveBuffer = new byte[48];
? ? ? ? ? ? DatagramPacket responsePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
? ? ? ? ? ? // 接收NTP響應(yīng)
? ? ? ? ? ? socket.receive(responsePacket);
? ? ? ? ? ? long ntpTime = parseNTPResponse(receiveBuffer);
? ? ? ? ? ? // 處理時(shí)間信息
? ? ? ? ? ? System.out.println("NTP服務(wù)器時(shí)間: " + ntpTime);
? ? ? ? ? ? // 關(guān)閉Socket連接
? ? ? ? ? ? socket.close();
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }
private static byte[] createNTPRequest() {
? ? ? ? // 構(gòu)建NTP請(qǐng)求消息? ? ? ? byte[] request = new byte[48];
? ? ? ? request[0] = 0x1B; // NTP協(xié)議版本號(hào)和操作碼? ? ? ? // 其他字段省略闷袒,可參考NTP協(xié)議文檔? ? ? ? return request;
? ? }
? ? private static long parseNTPResponse(byte[] response) {
? ? ? ? // 解析NTP響應(yīng)消息挟冠,提取時(shí)間信息? ? ? ? // 注意根據(jù)NTP協(xié)議的具體格式進(jìn)行解析? ? ? ? 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;
? ? }