Home > Uncategorized > Select outbound IP address on multi-homed server for HTTP requests

Select outbound IP address on multi-homed server for HTTP requests

If your server has multiple IP addresses, you can specify which IP address to make a HTTP request from in C#. This is useful if you want to need to ensure that requests do or do not originate from a particular IP address. This little console application demonstrates this, by listing available IP addresses, then making a request to an external website to reveal the outbound IP address as visible to the outside world.

private static IPAddress selectedIP;
static void Main(string[] args)
var ips = LocalIPAddress();
Console.WriteLine(“Select an IP Address”);
for (var i = 0; i < ips.Count(); i++)
Console.WriteLine(i + “. ” + ips[i]);
var choice = Console.Read() – 48 ;
selectedIP = ips[choice];
const string strUrl = “http://myexternalip.com/raw&#8221;;
var http = GetWebRequest(new Uri(strUrl));
var stream = http.GetResponse().GetResponseStream();
if (stream != null)
var sr = new StreamReader(stream);

protected static WebRequest GetWebRequest(Uri uri)
var request = (HttpWebRequest)WebRequest.Create(uri);
request.ServicePoint.BindIPEndPointDelegate = BindIPEndPointCallback;
request.Proxy = null;
return (request);

public static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
return new IPEndPoint(selectedIP, 0);

private static List<IPAddress> LocalIPAddress()
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
return null;
var host = Dns.GetHostEntry(Dns.GetHostName());
return host
.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).ToList();

To see it, you’ll need to run this on a multi-homed machine, type the number beside the required IP address, and see the external IP appear momentarily afterwards.

Categories: Uncategorized
  1. Sampath Sisira Kumara
    December 8, 2018 at 6:22 pm

    Thank you, this worked for me


  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: