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.