Skip to content

Instantly share code, notes, and snippets.

@coenm
Created May 10, 2024 14:57
Show Gist options
  • Save coenm/66b8d04f78edd498f9f41384e52bfd5d to your computer and use it in GitHub Desktop.
Save coenm/66b8d04f78edd498f9f41384e52bfd5d to your computer and use it in GitHub Desktop.
Change DNS using HttpClient
using System.Net;
using System.Net.Sockets;
namespace PocHttpClientCustomDns
{
// https://stackoverflow.com/questions/58547451/is-it-possible-to-set-custom-dns-resolver-in-cs-httpclient
// https://learn.microsoft.com/en-us/dotnet/api/system.net.http.socketshttphandler.connectcallback?view=net-5.0#System_Net_Http_SocketsHttpHandler_ConnectCallback
// https://csharpforums.net/threads/httpclient-custom-dns-ip.7486/#post-26692
// https://stackoverflow.com/questions/71638441/how-to-improve-slow-dns-with-httpclient
// https://stackoverflow.com/questions/37384945/how-to-force-ipv6-or-ipv4-for-httpwebrequest-or-webrequest-c-sharp/70475741#70475741
public class UnitTest1
{
[Fact]
public async Task Test1()
{
var dummyDnsHandler = new SocketsHttpHandler
{
ConnectCallback = async (context, cancellationToken) =>
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
try
{
// Use DNS to look up the IP address(es) of the target host
IPHostEntry ipHostEntry = await Dns.GetHostEntryAsync(context.DnsEndPoint.Host, cancellationToken);
// Filter for IPv4 addresses only
ipAddress = ipHostEntry.AddressList.First /*OrDefault*/(i => i.AddressFamily == AddressFamily.InterNetwork);
}
catch (System.Net.Http.HttpRequestException e)
{
// swallow, expected, not found
// No such host is known
}
catch (Exception e)
{
// swallow
}
// Fail the connection if there aren't any IPV4 addresses
if (ipAddress == null)
{
throw new Exception($"No IP4 address for {context.DnsEndPoint.Host}");
}
// Open the connection to the target host/port
TcpClient tcp = new();
await tcp.ConnectAsync(ipAddress, context.DnsEndPoint.Port, cancellationToken);
// Return the NetworkStream to the caller
return tcp.GetStream();
}
};
using var http = new HttpClient(dummyDnsHandler);
var rsp = await http.GetAsync("https://goasdfsadfasdfasdfasdfogle.com");
Assert.True(rsp.IsSuccessStatusCode);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment