tags:

views:

192

answers:

2

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.

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)?

+1  A: 
Nikolai N Fetissov
i'll try that. may be on localhost it should work.
iamrohitbanga
No, it's highly unlikely you'd be able to do that on a local host - the packets are just too fast :)
Nikolai N Fetissov
So executing symmetric connect()s on two hosts will establish a working TCP connection if the SYNs cross each other? Is listen() not required at all in this scenario?
sigjuice
Yes, **listen()** is not required, **bind()** is.
Nikolai N Fetissov
+1  A: 

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

Here's how I achieved a simultaneous open using a single Linux host.

  1. Slow down the loopback interface using netmem

    tc qdisc add dev lo root handle 1:0 netem delay 5sec
    
  2. Run netcat twice

    netcat -p 3000 127.0.0.1 2000
    netcat -p 2000 127.0.0.1 3000
    

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)

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
sigjuice
that is a very comprehensive answer. i tried it and learnt new things. thank you
iamrohitbanga
small correction. `tc qdisc replace` because on my pc it gives the error `RTNETLINK: file exists`. also i used the major and minor numbers from `ls -la /dev/loop0`.
iamrohitbanga
i am seeing multiple SYN's being exchanged consecutively. all with the same sequence number. any reason.
iamrohitbanga
you might try answering this:http://stackoverflow.com/questions/2264154/when-is-the-push-flag-set-in-tcp-segment
iamrohitbanga
@iamrohitbanga SYN's will get retransmitted until an ACK is received, which is why you see more than one with the same sequence number. I saw them too, but chose not to include them here.
sigjuice