Linux API to determine sockets owned by a process

后端 未结 7 1846
梦毁少年i
梦毁少年i 2020-12-23 02:01

Is there a Linux library that will enable me to tell what IP sockets are owned by what processes? I guess I\'m looking for the programmatic equivalent of lsof -i

7条回答
  •  我在风中等你
    2020-12-23 02:23

    /proc//net is equivalent to /proc/net for all processes in the same network namespace as you – in other words, it's "global" information.

    You can do what lsof and fuser do, which is to iterate through both /proc//fd/* and /proc/net/* looking for matching inodes. Quick demonstration:

    #!/bin/sh
    pgrep "$@" | while read pid; do
        for fd in /proc/$pid/fd/*; do
            name=$(readlink $fd)
            case $name in
                socket:\[*\])
                    ino=${name#*:}
                    for proto in tcp:10 tcp6:10 udp:10 udp6:10 unix:7; do
                        [[ ! -e /proc/net/${proto%:*} ]] ||
                        awk "
                            \$${proto##*:} == ${ino:1:${#ino}-2} {
                                print \"${proto%:*}:\", \$0
                                exit 1
                            }
                        " /proc/net/${proto%:*} || break
                    done
                    ;;
            esac
        done
    done
    

    You can extend this to other protocols (I see ax25, ipx, packet, raw, raw6, udplite, udp6lite in /proc/net/ too) or rewrite in a language of your choosing.

提交回复
热议问题