Search code examples
c#sql-serverdatasourcesqlconnection

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.


Solution

  • 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
    • ...