简体   繁体   English

如何使用.NET以编程方式将MSSQL服务器别名转换为IP地址?

[英]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. MSSQL客户端 附带 Windows默认安装 程序具有cliconfg应用程序,该应用程序用于为服务器IP地址和端口设置别名。 Sometimes we use in our ConnectionStrings some of those aliases instead of IP address,port. 有时我们在ConnectionStrings中使用其中的一些别名,而不是IP地址,端口。 How can I programatically translate that alias to an address using .NET? 如何使用.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. 更新: .NET + Windows在使用ConnectionString时会自动执行此转换,但是我不知道转换结果(IP地址)是否写在我们可以读取它的任何公共属性中。

Update: I discovered that the cliconfg stores the aliases in the Windows Registry. 更新:我发现cliconfg将别名存储在Windows注册表中。 I wonder if the Windows Registry is accessible from .NET 我想知道是否可以从.NET访问Windows注册表。

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: 我为Windows 32位版本找到了以下解决方案:

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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