Question

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!

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top