How to allow TCP connections from local host only

我的未来我决定 提交于 2019-12-13 04:53:33

问题


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);

I tried the following:

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

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);

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?

Thanks!


回答1:


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.

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.

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.



来源:https://stackoverflow.com/questions/17082531/how-to-allow-tcp-connections-from-local-host-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!