简体   繁体   中英

How get IP address or DNS name of SQL Server by connection?

I want know when my app run locally on SQL Server. It is necessary for backup and restore.

I get the IP address(DNS name) of the server from the Connection.DataSource. And then I check, whether there is this name in the list:

localNames = new List<string>() 
{ 
    ".", "localhost", "(local)", "127.0.0.1", Environment.MachineName.ToLower(),
};
localNames.AddRange(GetIP().Select(a=>a.ToString()));

if (localNames.Contains(GetServer(connection.DataSource).ToLower()))
{
    //do something
}

methods:

IEnumerable<IPAddress> GetIP()
{
    foreach (var ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork))
    {
        yield return ip;
    }
}

string GetServer(string dataSource)
{
    return dataSource.Split('\\').First().Split(',').First().Split(':').Last();
}

DataSource can be:

  • serverName1
  • serverName1,1433\\SQLEXPRESS
  • 192.168.0.1
  • tcp:192.168.0.1,1433\\SQLEXPRESS
  • ...

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