How do I clear System.Net client DNS cache?

前端 未结 4 1616
梦毁少年i
梦毁少年i 2020-12-03 04:26

I\'m using the .NET WebRequest while changing my HOSTS file. I\'m observing that System.Net doesn\'t honor those changes - how can I make it do so?

I have a number o

相关标签:
4条回答
  • 2020-12-03 05:13

    I finally dug up the obscure command from MSDN that fixes this:

    ServicePointManager.DnsRefreshTimeout = 0;
    

    As I unwound all the weird things I'd tried previously, I discovered one other setting that I need along with the one above; on the request object, turn off keep-alive:

    request.KeepAlive = false;
    
    0 讨论(0)
  • 2020-12-03 05:13

    you could use System.Diagnostics.Process to launch ipconfig /flushdns

    0 讨论(0)
  • 2020-12-03 05:15

    If you want to keep the DnsRefreshTimeout > 0 then you can update the cache by making a call to:

    System.Net.Dns.GetHostEntry("example.com");
    
    0 讨论(0)
  • 2020-12-03 05:16

    A late answer to be sure, but I found this solution worked better than the accepted answer. In my scenario I am testing SQL connections, and I couldn't apply the existing answer since I have no request.KeepAlive to set.

    This page by Brian Mancini ("derp turkey") details his adventure in clearing the DNS cache. Full props to him, I'm just adding his solution here:

    public class DnsUtils  
    {        
        [DllImport("dnsapi.dll", EntryPoint="DnsFlushResolverCache")]
        static extern UInt32 DnsFlushResolverCache();
    
        [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCacheEntry_A")]
        public static extern int DnsFlushResolverCacheEntry(string hostName);
    
        public static void FlushCache()
        {
            DnsFlushResolverCache();
        }
    
        public static void FlushCache(string hostName)
        {
            DnsFlushResolverCacheEntry(hostName);
        }
    }
    
    0 讨论(0)
提交回复
热议问题