简体   繁体   中英

How can I programatically translate a MSSQL server alias to an IP address using .NET?

The Windows default instalation comes with MSSQL client has a cliconfg application that is used to set aliases to Servers IP addresses and ports. Sometimes we use in our ConnectionStrings some of those aliases instead of IP address,port. How can I programatically translate that alias to an address using .NET?

Update: .NET + Windows automatically do this translation when we use the ConnectionString, but I don't know if the result of the translation (IP Address) is written in any public property where we can read it.

Update: I discovered that the cliconfg stores the aliases in the Windows Registry. I wonder if the Windows Registry is accessible from .NET

32bit HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo

64bit HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\MSSQLServer\Client\ConnectTo

I found the following solution for 32 bit versions of Windows:

using Microsoft.Win32;

static void Main(string[] args)
{
        var Aliases = Registry.LocalMachine.OpenSubKey(
            @"SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo");
        Aliases.GetValue("Alias");
}

只要不需要端口,使用System.Net.Dns类获取IP地址就很简单了:

IPAddress[] ips = Dns.GetHostAddresses("myHostName")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM