lua-users home
lua-l archive

Newbie udp socket question

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hello all,
I am a newbie to Lua and I was wondering whether somebody would give me
insight to the following:
1. I have trouble printing data returned from the UDP socket,
 When I print the data returned from the socket, it prints it in all
ascii, I know I have to do a unpack like feature available in PERL or
struct feature in Python, I dont know what is the equivalent in Lua. Can
somebody point give me a cluestick?
2. Is there a getopt like feature that I can use in lua.
program (intention is to print ntp time from a server, in other words,
sntp client, without modifications):
#!/usr/bin/env lua
-- $Id: sntp.lua,v 1.1 2007年05月15日 03:33:01 pgurumur Exp pgurumur $
ntp = {}
function ntp:Create(Server, Port)
 local socket = require "socket"
 local err = false
 sockTable = {}
 if Server then
 sockTable._server = Server
 end
 if Port then
 sockTable._port = Port
 end
 if not (sockTable._server and sockTable._port) then
 error("need server and port defined")
 end
 assert(socket.dns.toip(sockTable._server))
 sockTable._udpSocket = socket.udp()
 sockTable._udpSocket:setpeername(sockTable._server, sockTable._port)
 sockTable._udpSocket:settimeout(3)
end
function ntp:Send(Data)
 local sent = 0
 if Data then
 sent, err = sockTable._udpSocket:send(Data)
 if err then
 error("send " ..err)
 end
 end
 return sent
end
function ntp:Receive()
 local datagram, err = sockTable._udpSocket:receive()
 if not datagram then
 error("receive: " ..err)
 end
 return datagram
end
function GetInitData()
 data = string.format("%x", 0x23) .. string.rep("'0円'", 47)
 return data
end
port = 123
if arg[2] then
 port = arg[2]
end
if arg[1] then
 local host = arg[1]
 ntp:Create(host, port)
 ntp:Send(GetInitData())
 RetData = ntp:Receive()
 Data = string.format("%s", RetData)
 print(Data)
else
 print(arg[0] .. " hostname")
end
Thanks a lot in advance for your help
Prabhu
-

AltStyle によって変換されたページ (->オリジナル) /