如何创建一个服务器套接字,只允许特定 IP 连接

huangapple go评论59阅读模式
英文:

How to create a Server Socket to which only a specific IP can connect

问题

可以创建一个ServerSocket,在这个ServerSocket中,不使用ServerSocket的accept方法来处理任何连接,而是只等待并接受来自特定IP的连接吗?

或者,另一种方式是,在接受连接之前就能知道连接的IP,这样我就可以在不是特定IP的情况下拒绝连接吗?

英文:

Is it possible to create a ServerSocket where instead of using the ServerSocket#accept method for any connection, the ServerSocket waits and accepts a connection only from a specific IP?

Or, alternatively, is it possible to know the IP of a connection before accepting it so that I can reject it if it is not from that specific IP?

答案1

得分: 1

不,底层通信协议栈不支持在TCP套接字中实现这样的功能。

accept调用本身会返回一个套接字,然后可以查询该套接字以获取远程IP地址。如果IP地址不符合您的要求,您随后可以立即关闭该套接字。

(顺便说一下,您接受的是一个“连接”,而不是一个“套接字”。套接字只是一个本地数据结构,在每个端点上都有一个;在接受连接时,在您的计算机上创建套接字。这就好比您的电话和与另一端的通话之间的区别。)

英文:

No. The underlying communication stack does not support such a thing for TCP sockets.

The accept call itself returns a socket which can then be queried for the remote IP address. You can then immediately close the socket if the IP is not to your liking.

(By the way, what you accept is a 'connection', not a 'socket'. The socket is merely a local data structure, one at each endpoint; the socket is created on your machine in response to accepting a connection. It's the difference between your telephone and the conversation with the person at the other end.)

答案2

得分: 1

你不应该仅依赖源IP,因为很容易从另一台主机发送具有相同IP的TCP/IP数据包,参见IP欺骗。您需要使用SSL套接字以及一些身份验证来保护数据传输。

英文:

You shouldn't rely on the source IP, as it is easy to send TCP/IP packets with the same IP from another host, see IP spoofing. You need to use SSL sockets and some authentication over it.

答案3

得分: 0

没有很多关于特定的ServerSocket的经验,但对于TCP套接字有一些了解。我认为这是不可能的,然而你可以在接受连接之后验证IP地址(无论是TCP还是UDP套接字,都会接收到另一台机器的IP,因为提供响应是必要的)。

我不明白你这样做的原因(特别是考虑到IP地址通常会因为很多原因动态地改变),如果有其他方法可以解决你的问题的话。

英文:

Don't have a lot of experience with ServerSocket in specific, but have some with TCP sockets. I do not think this is possible, however what you can do is verify the IP address after an accept (both TCP and UDP sockets receive the IP of the other machine, since it is necessary to provide a response).

I do not see the reason you would do this (especially considering that IPs, usually, change dynamically over time for many reasons) and if there is another way to solve the problem you have.

答案4

得分: 0

在Java中不太确定,但在C或Python中是可能的。通过使用第3级原始套接字(raw socket),您可以在接受连接之前通过用RST数据包响应SYN数据包来阻止连接。

英文:

Not sure in java, but in c or python it is possible. With level 3 raw socket, you can prevent a connection, by responding SYN packets with RST packet, before accepting it.

huangapple
  • 本文由 发表于 2020年8月22日 20:34:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63536244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定