Question

I have a client-server application that uses .net remoting. The clients are in a LAN and i do not know their location in advance.

Sometimes we do file transfers and as an optimization I want to determine if a client is in fact on the same machine as the server (it is quite possible). In this case, I only need to do a File.Copy.

Let's say that a client calls the remote method:

RemoteFile server.GetFile(string path);

how can I determine if the client (the requester) is on the same machine?

Was it helpful?

Solution

If you know the IP Address for the server you're calling the remote method from you can use this method to tell whether or not you're on the same machine:

using System.Net;

private bool CheckIfServer(IPAddress serverIP)
{
    // Get all addresses assigned to this machine
    List<IPAddress> ipAddresses = new List<IPAddress>();
    ipAddresses.AddRange(Dns.GetHostAddresses(Dns.GetHostName()));

    // If desirable, also include the loopback adapter
    ipAddresses.Add(IPAddress.Loopback);

    // Detect if this machine contains the IP for the remote server
    // Note: This uses a Lambda Expression, which is only available .Net 3 or later
    return ipAddresses.Exists(i => i.ToString() == serverIP.ToString());
}

If you don't know the IPAddress for your remote server you can easily get it using the server's host name like this:

Dns.GetHostAddresses("remote_host_address")

This returns an IPAddress[], which includes all the resolved address for that host.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top