How to get a list of open sockets in Linux using C?

前端 未结 4 1522
名媛妹妹
名媛妹妹 2020-12-15 11:39

Is there a way to get a list of all open sockets ( socket address or socket descriptor ) in Linux using C in user-space or kernel?

Thank you

相关标签:
4条回答
  • 2020-12-15 12:25

    In directory /proc/self/fd there are fake symlinks giving you all your open file descriptors - sockets give something like:

    lrwx------ 1 root root 64 2009-05-08 07:45 4 -> socket:[4921]
    lrwx------ 1 root root 64 2009-05-08 07:45 5 -> socket:[4918]
    lrwx------ 1 root root 64 2009-05-08 07:45 6 -> socket:[5395]
    

    Iterate them using opendir, readdir() and then interrogate them using readlink()

    If you know that FD 4 is a socket, you can then call getsockname() on it to get the local address family, address etc, if bound.

    0 讨论(0)
  • 2020-12-15 12:32

    The raw data can be found at /proc/net/tcp, /proc/net/udp, etc. Refer to the header at the first line for a (terse) description.

    0 讨论(0)
  • 2020-12-15 12:35

    Open and read the following:

    /proc/net/tcp - a list of open TCP sockets

    /proc/net/udp - a list of open UDP sockets

    /proc/net/raw - a list all the "raw" sockets

    These are like "regular" files that you open and read with a filehandle and will give you all the information you could possibly need about each socket.

    0 讨论(0)
  • 2020-12-15 12:40

    This program may be useful for you and demonstrates how to parse the /net/proc/* files sockstat.c

    0 讨论(0)
提交回复
热议问题