簡體   English   中英

如何找到哪個進程綁定套接字但不監聽?

[英]how to find which process bind a socket but not listen?

當我使用nc來監聽端口時,它會顯示出來

nc -l -vv -p 21000

retrying local 0.0.0.0:21000 : Address already in use Can't grab 0.0.0.0:21000 with bind

但是我無法使用工具netstat / ss找到哪個任務占用了這個端口

netstat -an|grep 21000 

沒有找到

ss -a|grep 21000 

沒有找到

這個端口被我的java程序占用,代碼是:

public class Test1 {

        public static void main(String[] args) throws InterruptedException {
        Socket s = new Socket();
        try {
            s.bind(new InetSocketAddress("127.0.0.1",21000));
        } catch (IOException e) {
            e.printStackTrace();

        }
        Thread.sleep(500000000000L);
    }
}

當我綁定一個套接字,但不要與連接或監聽一起使用它。 我進入/ proc / [java task id] / fd,發現這個套接字的inode是“socket:[3073501]”但我找不到inode或端口,即使在/ proc / net / tcp或/ proc中也是如此/ NET / TCP6

是否有任何方法可以找到綁定套接字但不監聽或連接的進程。

謝謝。

我看到linux 3.10.0-327源代碼。 我認為文件/ proc / net / tcp的內容來自net / ipv4 / tcp_ipv4.c。

在tcp_proc_register方法中,

static void *tcp_get_idx(struct seq_file *seq, loff_t pos)      
{
        void *rc;
        struct tcp_iter_state *st = seq->private;

        st->state = TCP_SEQ_STATE_LISTENING;
        rc        = listening_get_idx(seq, &pos);

        if (!rc) {
                st->state = TCP_SEQ_STATE_ESTABLISHED;
                rc        = established_get_idx(seq, pos);
        }

        return rc;
}

它僅顯示偵聽中的socks或從tcp_hashinfo建立的socks。 但是tcp_hashinfo有三個結構

struct inet_bind_hashbucket     *bhash; 
struct inet_listen_hashbucket   listening_hash[INET_LHTABLE_SIZE];
struct inet_ehash_bucket        *ehash;

bhash可用於綁定。 但是不會在/ proc / net / tcp中導出。

我在Ubuntu下測試了你的Java程序。

如何找到綁定套接字但不監聽或連接的進程:

lsof的

lsof | grep "can't identify protocol"

您將得到如下結果:

COMMAND     PID   TID       USER   FD      TYPE             DEVICE SIZE/OFF    NODE NAME
java      29644 29653    stephan   12u     sock                0,7      0t0  312066 can't identify protocol

請注意TYPE sock和NAME can't identify protocol

這是如何運作的? 看看lsof的常見問題解答:

為什么/ proc-based lsof為某些套接字文件報告“無法識別協議”?

/ proc-based lsof可能會報告:

  COMMAND PID ... TYPE ... NODE NAME pump 226 ... sock ... 309 can't identify protocol 

這意味着它無法識別開放套接字文件使用的協議(即AF_ *指定)。 Lsof通過將與/ proc // fd條目關聯的節點編號與/ proc / net子目錄的所選文件中找到的節點編號進行匹配來標識協議。

...

您可能無法找到所需的節點號,因為並非所有內核協議模塊都完全支持/ proc / net信息。

驗證過程

lsof輸出中的PID為29644。

ls -l /proc/29644/fd   

這導致:

...
lrwx------ 1 stephan stephan 64 Jul  7 22:52 11 -> socket:[312064]
lrwx------ 1 stephan stephan 64 Jul  7 22:52 12 -> socket:[312066]
...

grep 312066 /proc/net/*

給出一個空的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM