如何只允许来自本地主机的 TCP 连接 [英] How to allow TCP connections from local host only

查看:57
本文介绍了如何只允许来自本地主机的 TCP 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望只能从本地主机(都来自 127.0.0.1my_local_ip)获取特定端口上的请求;

I want to be able to get request on a specific port only from localhost (both from 127.0.0.1 and my_local_ip);

我尝试了以下方法:

int localhost = (127 << 24) + 1; // 127.0.0.1     
sock_address.sin_addr.s_addr = htonl(localhost);    

这让我只能连接 127.0.0.1 而不是从实际的本地 ip.我也试过:

This lets me connect only with 127.0.0.1 but not from the actual local ip. I also tried:

char hostName[128] = "";
struct hostent     *pHost        = 0;
gethostname(hostName, sizeof(hostName));
pHost = gethostbyname(hostName);
memcpy(&sock_address.sin_addr, pHost->h_addr_list[0], pHost->h_length);

由于我无法连接127.0.0.1,我能够连接本地IP,但远程请求也得到响应

By that I wasnt able to connect with 127.0.0.1, I was able to connect with local ip, but remote requests were also answered

我做错了什么?还有其他办法吗?

What am I doing wrong? Is there any other way?

谢谢!

推荐答案

在您的应用程序中,您只能设置端口将绑定到哪些接口.在第一种情况下,您将其绑定到环回接口(lo,IP 地址 127.0.0.1),这意味着只有您可以连接到它,因为只有您自己的主机才能访问那个界面.如果您将端口绑定到外部接口,例如 eth0 和 IP 地址 10.1.2.3,如果没有防火墙阻止连接,外部主机可能能够连接到该端口请求.

From your application you can only set to which interfaces the port will be bound. In the first case you bound it to the loopback interface (lo, IP address 127.0.0.1) and that means that only you can connect to it because only your own host reaches that interface. If you bind the port to an external interface, eth0 with IP address 10.1.2.3 for example, external hosts might be able to connect to that port if no firewall blocks the connection request.

做您想做的事情的唯一方法是设置本地计算机的数据包过滤器(防火墙),以拒绝/丢弃来自未被识别为您自己的 IP 地址的特定端口的连接请求(SYN 数据包).在这种情况下,远程主机会认为您的 TCP 端口已关闭或被阻止,具体取决于您设置过滤器的方式.

The only way to do what you want is by setting up the packet filter (firewall) of your local machine to deny/drop connection requests (SYN packets) to that specific port incoming from IP addresses that are not recognized as your own. In this case the remote host would think that your TCP port is closed or blocked, depending on how you set the filter.

好吧……如果远程主机不是您自己的 IP 地址之一,您也可以接受来自任何接口的任何连接并立即关闭它,但出于某种原因,我想这正是您真正想要的.

Well... you could also accept any connection from any interface and instantly close it if the remote host is not one of your own IP addresses, but for some reason I guess that's what you really want.

这篇关于如何只允许来自本地主机的 TCP 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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