![]() |
|
Lua sockets - Printable Version +- Sinisterly (https://sinister.li) +-- Forum: Coding (https://sinister.li/Forum-Coding) +--- Forum: Coding (https://sinister.li/Forum-Coding--71) +--- Thread: Lua sockets (/Thread-Lua-sockets) |
Lua sockets - noize - 05-27-2013 Lua sockets Lua's HTTP and TCP sockets. Basic knowledge of general computer programming, sockets and Lua is required to completely understand the content of this page. HTTP sockets For the first way to handle an HTTP socket in Lua we'll use the "request" function. The request function can be used in a string-based simple form to download a URL using either the POST or the GET method or in a LTN12-based generic form capable of using any HTTP method. These are the constants that control the HTTP module: http://w3.impa.br/~diego/software/luasocket/http.html Wrote:PORT: default port used for connections; In the above example, http (in http.request) is a variable: Code: http = require "socket.http"This is an example usage of http.request: Code: local http = require("socket.http")
local ltn12 = require("ltn12")
http.request{
url = "http://www.server.com/text.txt",
sink = ltn12.sink.file(io.stdout)
}The above script will download test.txt's data, output it and then discard it. If you wanted to save the downloaded data to a local file (let's say file.txt), you could use: Code: sink = ltn12.sink.file(io.open("file.txt","w"))Another way to retrieve data using the HTTP protocol could be: Code: require("socket")
s = socket.connect(host,port)
s:send("GET / HTTP/1.0\r\n\r\n")
while true do
s, status, partial = client:receive(1024)
print (s or partial)
if status == "closed" then break end
end
s:close()TCP sockets Code: socket = require("socket")
s = socket.tcp()
assert(s:connect(host, port), "Error! Connection failed!") -- attempts to connect to the server. in case of failure, it returns the error message.
-- Example:
-- assert(s:connect("www.google.com",80))
s:settimeout(0) -- set the timeout for the "s" object to 0 to avoid freezing.
s:send("This data is sent to the host through the port.\r\n")
s:close()This is a code to handle incoming data through the TCP protocol: Code: s = assert(socket.bind(host, port))
i, p = s:getsockname()
assert(i, p)
print("Listening...")
data = assert(s:accept())
print("Connection established, now printing received data...")
rcv, endd = data:receive()
while not endd do
print(rcv)
rcv, endd = data:receive()
end
print(endd)Sources: http://w3.impa.br/~diego/software/luasocket/http.html Special thanks to: @JesseH, @asiktumar. RE: Lua sockets - noize - 06-29-2013 Update: added sample script to handle incoming data. PoC to send/receive data on localhost: http://www.hackcommunity.com/Thread-Lua-TCP-RAT-PoC . |