Tag Archive Server


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

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 ipAddresses = new List();

    // If desirable, also include the loopback adapter

    // 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.