开发者

Display socket options

开发者 https://www.devze.com 2022-12-12 18:49 出处:网络
How I can see from shell what socket options are set? In particular I\'m in开发者_如何学Goteresting to know if SO_BROADCAST is set?You can use lsof(8).If PID is the process ID and FD is the file desc

How I can see from shell what socket options are set? In particular I'm in开发者_如何学Goteresting to know if SO_BROADCAST is set?


You can use lsof(8). If PID is the process ID and FD is the file descriptor number of the socket you're interested in, you can do this:

lsof -a -p PID -d FD -T f

To list all IPv4 sockets of a process:

lsof -a -p PID -i 4 -T f

This will print out the socket options with a SO=, among other information. Note that if no options are set, you'll get the empty string, so you'll see something like SO=PQLEN=0 etc. To test for SO_BROADCAST, just grep for the string SO_BROADCAST after the SO=, e.g.

if lsof -a -p PID -d FD -T f | grep -q 'SO=[^=]*SO_BROADCAST'; then
    # socket has SO_BROADCAST
else
    # it doesn't
fi


On Linux, you can use the knetstat kernel module to inspect socket options, including SO_BROADCAST.


I had the same issue today; unfortunately, on my system, the -T option of lsof doesn't accept the f flag, and I also didn't want to build the knetstat kernel module.

Luckily, I was in the position of being able to strace the application while it was setting up the socket, like this:

strace -e trace=setsockopt -f -o /tmp/log ./program arg1 arg2

This traces ./program arg1 arg2, writing the trace to /tmp/log. We only trace the setsockopt() system call, which is used to set socket options. The option -f makes strace also trace any child processes created by the traced program.

If you are lucky, /tmp/log will contain lines like this one:

18806 setsockopt(60, SOL_SOCKET, SO_KEEPALIVE, [1], 4) = 0

This indicates that process 18806 called setsockopt() on FD 60 to set SO_KEEPALIVE to 1 (enabling it), and that the system call succeeded with return code 0.

It's also possible to attach to an existing process:

strace -e trace=setsockopt -f -o /tmp/log -p PID

You can detach from the process using CTRL-C, and omit the -o option and its argument to send the trace to stderr.

0

精彩评论

暂无评论...
验证码 换一张
取 消