lua獲取網絡當前時間戳


使用luasocket

local socket = require "socket.core"
local server_ip = {
        "time-nw.nist.gov",
        "time-a.nist.gov",
        "time-b.nist.gov",
        "time.nist.gov",
        "time-c.nist.gov",
        "time-d.nist.gov",
    }

function nstol(str)
    assert(str and #str == 4)
    local t = {str:byte(1,-1)}
    local n = 0
    for k = 1, #t do
        n= n*256 + t[k]
    end
    return n
end

-- get time from a ip address, use tcp protocl
function gettime(ip)
    print('connect ', ip)
    local tcp = socket.tcp()
    tcp:settimeout(10)
    tcp:connect(ip, 37)
    success, time = pcall(nstol, tcp:receive(4))
    tcp:close()
    return success and time or nil
end

function nettime()
    for _, ip in pairs(server_ip) do
        time = gettime(ip)
        if time then 
            --print(os.date("%c", time-2208988800))
            print(time-2208988800)
            --return time-2208988800
        end
    end
end

nettime()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM