2010-12-08 154 views
2

我遇到一個奇怪的偶然事件,其中的我傳出TCP端口匹配監聽端口

lsof | grep 40006 

結果產生

java  29722  appsrv 54u  IPv6   71135755  0t0  TCP localhost:40006->localhost:40006 (ESTABLISHED) 

一般來說,我看到

java  30916  appsrv 57u  IPv6   71143812  0t0  TCP localhost:43017->localhost:40006 (ESTABLISHED) 

在港口做不符合箭頭的任一側。雖然lsof正在生成前一個結果,但我無法啓動嘗試偵聽端口40006的應用程序,即使套接字配置爲SO_REUSEADDR。

這可能發生嗎?應該是?

UNAME給出:Linux的femputer 2.6.32-24服務器#39,Ubuntu的SMP週三7月28日6點21分40秒UTC 2010 x86_64的GNU/Linux的

+0

注意:對於第一個lsof結果,在40006上監聽的應用程序已終止。 – user535674 2010-12-08 22:36:00

回答

1

可以通過創建套接字來安排這種連接,將其綁定到127.0.0.1:40006,然後將其connect()127.0.0.1:40006。 (注意:沒有listen())。我相信這被稱爲「積極主動開放」。

下面的程序說明了這一點:

#include <stdio.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <unistd.h> 

int main() 
{ 
    int s; 
    struct sockaddr_in sa = { 
     .sin_family = PF_INET, 
     .sin_port = htons(40006), 
     .sin_addr.s_addr = htonl(INADDR_LOOPBACK) }; 

    s = socket(PF_INET, SOCK_STREAM, 0); 

    if (s < 0) { 
     perror("socket"); 
     return 1; 
    } 

    if (bind(s, (struct sockaddr *)&sa, sizeof sa) < 0) { 
     perror("bind"); 
     return 1; 
    } 

    if (connect(s, (struct sockaddr *)&sa, sizeof sa) < 0) { 
     perror("connect"); 
     return 1; 
    } 

    pause(); 

    return 0; 
} 

的原因,不能再使用的端口是因爲口不聽 - 這是一個輸出端口。

0

難道這兩個端口40006分別在不同的接口?

+0

計算機上只有一個接口。 – user535674 2010-12-08 23:35:20

+0

除非在lo和eth0之間做出區分,因爲這兩個應用程序都位於同一臺計算機上,並通過主機名localhost進行連接。 – user535674 2010-12-08 23:37:24