在本地主机上使用相同的IP和端口创建套接字 [英] Socket getting created with same IP and port on local host

查看:41
本文介绍了在本地主机上使用相同的IP和端口创建套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到Linux上的行为很奇怪,在那里我看到远端和本地端都显示相同的IP和端口组合.以下是netstat的输出

I am seeing weird behavior on Linux where I am seeing that remote end and local end are both showing same IP and port combination. Following is the netstat output

netstat -anp |grep 6102

netstat -anp | grep 6102

tcp 0 0 139.185.44.123:61020 0.0.0.0:* LISTEN 3361/a.out
tcp 0 0 139.185.44.123:61021 139.185.44.123:61021建于3361/a.out

tcp 0 0 139.185.44.123:61020 0.0.0.0:* LISTEN 3361/a.out
tcp 0 0 139.185.44.123:61021 139.185.44.123:61021 ESTABLISHED 3361/a.out

谁能告诉我这是否可能?如果是,那么可能是什么情况?

Can anyone tell me if this is even possible ? If yes, then what could be the scenario ?

推荐答案

连接由4元组((源ip,源端口),(目标ip,目标端口))以及源端口和目标端口标识可以想象是一样的,没有任何问题.甚至可以通过一个过程建立此连接,这将导致您看到的输出.

A connection is identified by a 4-tuple ((source ip, source port), (target ip, target port)), and the source and target ports could conceivably be the same without any issues. This connection could even be established by one process, which would lead to the output you're seeing.

但是,我只是被一个讨厌的bug所咬住,在该bug中,客户端套接字将尝试使用同一计算机上临时端口范围内的端口号连接到服务器套接字.连接操作将重试,直到成功.

However, I just got bitten by a nasty bug, where a client socket would try to connect to a server socket with a port number in the ephemeral port range on the same machine. The connection operation would be retried operation until it succeeded.

重试功能是一个问题:如果服务器应用程序未在运行,并且随机选择的源端口与目标端口相同(这可能是因为目标端口在临时范围内),客户端套接字将连接到自己(您可以想象,这对客户端应用程序的内部逻辑造成了严重破坏).

The retry feature was the issue: if the server application wasn't running AND the source port that got picked at random was the same as the target port (which is possible because the target port was in the ephemeral range), the client socket would CONNECT TO ITSELF (which was wreaking havoc on the internal logic of the client application, you can imagine).

由于客户要尽快执行重试,所以这种情况可能发生的几千分之三的命中率就足够快了.

Since the client was performing retries as quickly as possible, the 1 in 30.000 odds that this can happen were hit quickly enough.

以下Python脚本复制了它:

The following Python script reproduces it:

import socket

host = 'localhost'
port = 35911

ctr = 0
while True:
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(5)
        ctr += 1
        s.connect((host, port))
        print "Connected to self after", ctr, "tries"
        break
    except socket.error, e:
        print e
        # Retry

这篇关于在本地主机上使用相同的IP和端口创建套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆