Xamarin Forms application - Force IPv4 to HttpClient

252 views Asked by At

It appears that this can be achieved by setting up a callback function to the ServicePoint.

The solution (although the goal is different, the same technique can be used) is discussed in this question Specify the local endpoint for HTTP request.

Following it, I tried

var servicePoint = ServicePointManager.FindServicePoint(new Uri(uri));
servicePoint.BindIPEndPointDelegate = (servicePoint, remoteEndPoint, retryCount) =>
{
  if (remoteEndPoint.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  {
    return new IPEndPoint(IPAddress.Any, 0);
  }

  throw new InvalidOperationException("no IPv4 address");
};

var _client = new HttpClient();
HttpResponseMessage response = await _client.GetAsync(uri);

expecting that the callback is called at the GetAsync() but it is not.

It would be much appreciated if someone tells me what I am missing. Or, a completely different approach to achieve my goal, to force IPv4 at connections that HttpClient makes, would also be very much welcome.

Thanks in advance for your help.

Update

In the question How to use HttpClient to send a Request from a specific IP address? C#, someone says "... the .net core team have implemented the HttpClientHandler etc without bothering to put anything related to service points in there ..." To confirm, I build the above code both with Framework4.7 and Core3.1 to find out that indeed, when built with Core, the callback is NOT called.

A Xamarin project targets .Net standard, which is a Core if I am not mistaken. I guess I need to forget this ServicePoint stuff and look for other solutions...

Again, your insight will be very much appreciated!

0

There are 0 answers