问题描述
考虑 TCP 的三向握手.在此处进行了说明.
Consider the three way handshake of TCP. It is explained here.
现在上面的文章提到了两端可能会同时尝试连接,在这种情况下,三向握手可以正常工作.
Now the article above mentions that two sides may try to connect simultaneously and the three way handshake works fine in this case.
我们可以使用sockets api来模拟这种情况吗?我们通常使用套接字编码的是被动开放(服务器)和主动开放(客户端)?
Can we simulate this situation using the sockets api.what we usually code using sockets is a passive open(server) and an active open(client)?
推荐答案
使用套接字 API 可能导致同时打开 TCP.正如 Nikolai 所提到的,这是一个以初始 SYN 相互交叉的时间执行以下序列的问题.
It is possible to cause a simultaneous TCP open using the sockets API. As Nikolai mentions, it is a matter of executing the following sequence with a timing such that the initial SYNs cross each other.
bind addr1, port1
connect addr2, port2
bind addr2, port2
connect addr1, port1
这是我如何使用单个 Linux 主机实现同时打开.
Here's how I achieved a simultaneous open using a single Linux host.
使用 netem
tc qdisc add dev lo root handle 1:0 netem delay 5sec
运行 netcat
两次
netcat -p 3000 127.0.0.1 2000
netcat -p 2000 127.0.0.1 3000
两个 netcat 进程相互连接导致一个 TCP 连接
The two netcat processes connect to each other resulting in a single TCP connection
$ lsof -nP -c netcat -a -i # some columns removed
COMMAND PID NAME
netcat 27911 127.0.0.1:2000->127.0.0.1:3000 (ESTABLISHED)
netcat 27912 127.0.0.1:3000->127.0.0.1:2000 (ESTABLISHED)
这是 tcpdump 向我展示的内容(为了清晰起见,对输出进行了编辑)
Here's what tcpdump showed me (output edited for clarity)
127.0.0.1.2000 > 127.0.0.1.3000: Flags [S], seq 1139279069
127.0.0.1.3000 > 127.0.0.1.2000: Flags [S], seq 1170088782
127.0.0.1.3000 > 127.0.0.1.2000: Flags [S.], seq 1170088782, ack 1139279070
127.0.0.1.2000 > 127.0.0.1.3000: Flags [S.], seq 1139279069, ack 1170088783
这篇关于tcp 两端试图同时连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!