Thursday, September 14, 2017

Can I find out the status of the port using the Lua “socket” library?

Leave a Comment

Help me track the status of a specific port: "LISTENING", "CLOSE_WAIT", "ESTABLISHED". I have an analog solution with the netstat command:

local command = 'netstat -anp tcp | find ":1926 " ' local h = io.popen(command,"rb") local result = h:read("*a") h:close() print(result) if result:find("ESTABLISHED") then    print("Ok") end 

But I need to do the same with the Lua socket library. Is it possible?

2 Answers

Answers 1

Like @Peter said, netstat uses the proc file system to gather network information, particularly port bindings. LuaSockets has it's own library to retrieve connection information. For example,

Listening you can use master:listen(backlog) which specifies the socket is willing to receive connections, transforming the object into a server object. Server objects support the accept, getsockname, setoption, settimeout, and close methods. The parameter backlog specifies the number of client connections that can be queued waiting for service. If the queue is full and another client attempts connection, the connection is refused. In case of success, the method returns 1. In case of error, the method returns nil followed by an error message.

The following methods will return a string with the local IP address and a number with the port. In case of error, the method returns nil.

master:getsockname() client:getsockname() server:getsockname() 

There also exists this method: client:getpeername() That will return a string with the IP address of the peer, followed by the port number that peer is using for the connection. In case of error, the method returns nil.

For "CLOSE_WAIT", "ESTABLISHED", or other connection information you want to retrieve, please read the Official Documentation. It has everything you need with concise explanations of methods.

Answers 2

You can't query the status of a socket owned by another process using the sockets API, which is what LuaSocket uses under the covers.

In order to access information about another process, you need to query the OS instead. Assuming you are on Linux, this usually means looking at the proc filesystem.

I'm not hugely familiar with Lua, but a quick Google gives me this project: https://github.com/Wiladams/lj2procfs. I think this is probably what you need, assuming they have written a decoder for the relevant /proc/net files you need.

As for which file? If it's just the status, I think you want the tcp file as covered in http://www.onlamp.com/pub/a/linux/2000/11/16/LinuxAdmin.html

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment