Resolved HttpClient custom dns/ip

Marcos Santos

Member
Joined
Nov 11, 2021
Messages
11
Programming Experience
1-3
I have a vps with a console program in C# which makes a request to my api.

my vps has 3 ips and I wanted to achieve to send each request over the different ips.

How do I do it? This is what I found so far, but I am still confused if its.

C#:
public static HttpClient GetHttpClient(IPAddress address)
{
    if (IPAddress.Any.Equals(address))
        return new HttpClient();

    SocketsHttpHandler handler = new SocketsHttpHandler();

    handler.ConnectCallback = async (context, cancellationToken) =>
    {
        Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);

        socket.Bind(new IPEndPoint(address, 0));

        socket.NoDelay = true;

        try
        {
            await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false);

            return new NetworkStream(socket, true);
        }
        catch
        {
            socket.Dispose();

            throw;
        }
    };

    return new HttpClient(handler);
}
 
Last edited:
What exact problem are you running into with the code above?

How exactly are you calling GetHttpClient() ? What are you passing in as the address parameter?
 
my vps has 3 ips and I wanted to achieve to send each request over the different ips.
In general, it would be better to use a dedicated load balancer on the server side instead of trying to do a poor man's load balancing by doing a round robin on the IPs that you use from the client side.
 
What exact problem are you running into with the code above?

How exactly are you calling GetHttpClient() ? What are you passing in as the address parameter?

In general, it would be better to use a dedicated load balancer on the server side instead of trying to do a poor man's load balancing by doing a round robin on the IPs that you use from the client side.

Actually it works, I wanted to send the same request but with a different ip, my vps has multiples IPs
 

Latest posts

Back
Top Bottom