Linux/Unix套接字自连接 [英] Linux/Unix Socket Self-connection

查看:120
本文介绍了Linux/Unix套接字自连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当客户端尝试连接到服务器时,如果客户端和服务器都是本地主机,则可能会发生自连接(源端口和目标端口碰巧相同).但是我的问题是,客户端没有在监听该端口,怎么可能进行自连接?

When a client try to connect to a server, if client and server are both localhost, self-connection may happen(source port and destination port happened to be the same.). But my problem is, client is not listening to that port, how can self-connection be possible?

推荐答案

我们可以使用以下python程序简单地重现这种现象

We can simple reproduce this phenomenon with the following python program

import socket
for i in range(65536):
  try:
    s = socket.create_connection(('127.0.0.1', 50000))
    print 'connected to {0}'.format(s.getpeername())
  except Exception as e:
    pass

当我们尝试在同一主机中连接某些套接字时.如果我们不将您的客户端绑定到特定端口,则操作系统将为您提供ephemeral port.如果碰巧是您要连接的那个.它导致自我连接.确保您要连接的端口在/proc/sys/net/ipv4/ip_local_port_range

when we try to connect some socket in the same host. if we don't bind your client to a specific port, operating system will provide ephemeral port for you. if it's happened to be the one you want to connect to. it causes self connection. Make sure the port you are trying to connect is in /proc/sys/net/ipv4/ip_local_port_range

这篇关于Linux/Unix套接字自连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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