I want to make a web request from one of available IP addresses on server so I use this class:
public class UseIP
{
public string IP { get; private set;
I like this new class UseIP.
There is a point at Specify the outgoing IP Address to use with WCF client about protecting yourself from IPv4/IPv6 differences.
The only thing that would need to change is the Bind method to be like this:
private IPEndPoint Bind(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
if ((null != IP) && (IP.AddressFamily == remoteEndPoint.AddressFamily))
return new IPEndPoint(this.IP, 0);
if (AddressFamily.InterNetworkV6 == remoteEndPoint.AddressFamily)
return new IPEndPoint(IPAddress.IPv6Any, 0);
return new IPEndPoint(IPAddress.Any, 0);
}
re: the Bind method being called multiple times.
What works for me is to remove any delegate link before I add it.
ServicePoint servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.BindIPEndPointDelegate -= this.Bind; // avoid duplicate calls to Bind
servicePoint.BindIPEndPointDelegate += this.Bind;
I also like the idea of caching the UseIP objects. So I added this static method to the UseIP class.
private static Dictionary _eachNIC = new Dictionary();
public static UseIP ForNIC(IPAddress nic)
{
lock (_eachNIC)
{
UseIP useIP = null;
if (!_eachNIC.TryGetValue(nic, out useIP))
{
useIP = new UseIP(nic);
_eachNIC.Add(nic, useIP);
}
return useIP;
}
}