07-17-07 06:24 AM
chsalvia@gmail.com wrote:
> What is the best way to limit a socket connection to local clients? I
> implemented this by doing a call to getpeername(), then simply
> checking if the sockaddr struct is either 127.0.0.1, or 192.168.*.*.
>
> Is that the best way to do it, or is there some better way?
First, I don't know why you'd check for 192.168.*.* but not also
check for 10.*.*.* and 176.{16-31}.*.*.
Having said that, I don't know why you'd hard code any set of
addresses. Someone else made a very good point, which is that you
need to define what "local" means, which you haven't yet done.
Since you appear to be limiting yourself to IPv4 specifically,
I'd like to suggest that a natural definition is that a client
is local if its address does not have to be routed at the IP
layer. Whatever layer is below IP (whether it's PPP or Ethernet
or Token Ring or even SCSI or CDDI) might route it, but in the
definition I'm suggesting, none of that matters, even if the
"local" machine is 10,000 miles away.
If that's what you'd like to do, then one way to do it is to
enumerate over the interfaces on the machine, and collect
their IP addresses and netmasks. Then a host is "local" if
the following expression is true:
(remote_addr & netmask == interface1_addr & netmask)
|| (remote_addr & netmask == interface2_addr & netmask)
..
|| (remote_addr & netmask == interfaceN_addr & netmask)
Of course, this is entirely an arbitrary distinction, but it's
just as useful as anything else that doesn't require manual
configuration of the definition of "local".
Now, finding a portable way of iterating over the interfaces
is something I've never tried to do, so I don't know if it's
easy or hard.
- Logan
[ Post a follow-up to this message ]
|