Posts Tagged ‘TCP/IP’

C#: Detect If You’re Running on the Server

April 27th, 2009

If you ever need to detect whether your code is running on the machine that you’re talking to through IP (a server application for example), and you know the IP address for the remote machine, then this code may come in handy. It was originally written by my buddy Erin for a project we both worked on.

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.x
    return ipAddresses.Exists(i => i.ToString() == serverIP.ToString());
}

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

IPAddress[] addresses = Dns.GetHostAddresses("remote_host_address");

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