views:

111

answers:

3

I'm working with socket and to this I'm using TIdTCPClient and TIdTCPServer. I need to check if the TIdTCPServer that the TIdTCPClient connected is on the same network.

How can I do this ?

at.

+1  A: 

What do you mean for "same network"? You could mimic the traceroute utility and check how many hops (with their addresses of routers) are, and compare with the expected ones.

ldsandon
+6  A: 

You need to know the client's subnet mask in order to do that kind of comparison. Sockets do not expose that information, so you will have to ask the OS directly (for instance, on Windows, you can look for the client's connected local IP in the list returned by GetAdaptersInfo() or GetAdapterAddresses()). Once you have the mask, you can then mask the client's IP and the server's IP with it and see if the resulting values are the same.

Remy Lebeau - TeamB
Just to be complete (clientip and netmask)=(destinationip and netmask)
Marco van de Voort
Yes. For IPv4 IPs, anyway (GetAdaptersInfo() only supports IPv4). It gets a little more complicated with IPv6 IPs.
Remy Lebeau - TeamB
That would be the same "subnet" not the same "network". Network is a much more broader definition, a whole company LAN network could be made up of several subnets.
ldsandon
AFAIK, there is no direct way to determine what other subnets are available on the local network, only what the local subnet is. In that regard, then yes, a traceroute would be needed. If it encounters the network's public Internet IP before encountering the server's IP, then the server is not on the local network.
Remy Lebeau - TeamB
A: 

Tks for hits, to solve my case I just needed to verify if the host is a local host or not.

The solution:

function IsLocalHost(AHost : string) : Boolean;
var
  LStrRegexRedeLocal : string;
begin
  if LowerCase(AHost) = 'localhost' then
    result := True
  else
  begin
    LStrRegexRedeLocal := '(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)|(^127\.0\.0\.1)';
    result := ExecRegExpr(LStrRegexRedeLocal, AHost);
  end;
end;
SaCi