I am trying to specify the local endpoint for some HTTP requests that I need to send.
So, I have multiple IPs on my device (Wifi and Cellular) and would like to chose which one of those I want to use when sending HTTP request to get/post data from the server.
I learned that it is possible with HttpClient with .NET core 5.0 (that isn't supported with Xamarin) HttpClient specify interface to bind to / make requests from
SocketsHttpHandler socketsHttpHandler = new SocketsHttpHandler();
socketsHttpHandler.ConnectCallback = async (context, token) =>
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Loopback, 0));
await s.ConnectAsync(context.DnsEndPoint, token);
s.NoDelay = true;
return new NetworkStream(s, ownsSocket: true);
};
using (HttpClient Client = new HttpClient(socketsHttpHandler))
{
Client.BaseAddress = new Uri("PutIPHere//");
HttpResponseMessage Response = await Client.GetAsync("");
// use Response as needed...
}
Another way is with reflection (but only with .NET framework), see L.B Answer
HttpClientHandler SetServicePointOptions(HttpClientHandler handler)
{
var field = handler.GetType().GetField("_startRequest", BindingFlags.NonPublic | BindingFlags.Instance); // Fieldname has a _ due to being private
var startRequest = (Action<object>)field.GetValue(handler);
Action<object> newStartRequest = obj =>
{
var webReqField = obj.GetType().GetField("webRequest", BindingFlags.NonPublic | BindingFlags.Instance);
var webRequest = webReqField.GetValue(obj) as HttpWebRequest;
webRequest.ServicePoint.BindIPEndPointDelegate = new BindIPEndPoint(BindIPEndPointCallback);
startRequest(obj); //call original action
};
field.SetValue(handler, newStartRequest); //replace original 'startRequest' with the one above
return handler;
}
private static IPEndPoint BindIPEndPointCallback(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount)
{
return new IPEndPoint(IPAddress.Parse("PutIPHere"), 0);
}
Is there any way to specify the local endpoint for HTTP requests (using Xamarin)? I would like to do it from the PLC, but also native to android and iOS should be ok. Thanks in advance