windows - Why can a socket connect() to its own ephemeral port? -


i can reliably winsock socket connect() if connect localhost port in range of automatically assigned ephemeral ports (5000–65534). specifically, windows appears have system-wide rolling port number next port try assign local port number client socket. if create sockets until assigned number below target port number, , repeatedly create socket , attempt connect port number, can socket connect itself.

i first got happen in application repeatedly tries connect port on localhost, , when service not listening establishes connection , receives message sent (which happens redis ping command).

an example, in python (run nothing listening target port):

import socket  target_port = 49400  def mksocket():     return socket.socket(socket.af_inet, socket.sock_stream, socket.ipproto_tcp)  while true:     sock = mksocket()     sock.bind(('127.0.0.1', 0))     host, port = sock.getsockname()     if port > target_port - 10 , port < target_port:         break     print port  while port < target_port:     sock = mksocket()     err = none     try:         sock.connect(('127.0.0.1', target_port))     except socket.error, e:         err = e     host, port = sock.getsockname()     if err:         print 'unable connect port %d, used local port %d: %s' % (target_port, port, err)     else:         print 'connected port %d, used local port %d' (target_port, port) 

on mac machine, terminates unable connect port 49400, used local port 49400. on windows 7 machine, connection established , prints connected port 49400, used local port 49400. resulting socket receives data sent it.

is bug in winsock? bug in code?

edit: here screenshot of tcpview offending connection shown:

python.exe 8108 tcp (my hostname) 49400 localhost 49400 established

this appears 'simultaneous initiation' described in #3.4 of rfc 793. see figure 8. note neither side in state listen @ stage. in case, both ends same: cause work described in rfc.


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -