問題描述
兩個進程使用同一個端口? (Two processes using the same port?)
So I was looking into what port dropbox uses on my computer and tried to see what would happen if i created a new http server on that port. Surprisingly it worked. So both dropbox and my http server were running on the same port, but the incoming requests were routed to the different application depending on the source address.
lsof ‑i tcp:51311
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
Dropbox 3811 user 18u IPv4 0xdedc291239eb197f 0t0 TCP 172.20.10.2:51311‑>108.160.163.34:http (ESTABLISHED)
node 3984 user 11u IPv4 0xdedc29123b1494cf 0t0 TCP *:51311 (LISTEN)
I am wondering how this works. I thought the os would refuse the bind my http server since the port was already alloted to dropbox but to my surprise it worked. Anyone thoughts?
參考解法
方法 1:
TCP sockets match against the 4‑tuple (source‑ip, source‑port, destination‑ip, destination‑port). As long as all four of them don't clash, you can have port reuse.
As long as your daemon doesn't receive a connection from 108.160.163.34:80
your stack can handle it. If the server 108.160.163.34
is well‑behaved it won't let an application initiate a connection to your socket (172.20.10.2:51311
) with 80 as source port. (bind()
should fail with Address already in use
).
If it isn't well behaved, the existing dropbox connection will receive an unexpected packet (wrong sequence number space) and your stack will RST
it.
方法 2:
The HTTP port being used by Dropbox is at 108.160.263.34, not your local host.
Port 51311 is being used as one outbound port and one listening port. Not 'two services running on the same port'. Otherwise there would be two LISTENING lines.
(by omgpython、jman、user207421)