SqlConnection - is remote or local connection?

后端 未结 4 1332
星月不相逢
星月不相逢 2021-01-27 20:20

How can I determine is it local connection (localhost or 127.0.0.1) or is it remote connection (other machine in local area) if I have SqlConnection object?

相关标签:
4条回答
  • 2021-01-27 21:09

    You can get the connection string out of the SqlConnection obejct.

    string s = connection.ConnectionString;
    

    and check the data source or the server element of that string.

    Edit: Code sample provided.

    I think this function should work (not tested anyways).

    private bool CheckConnectionStringLocalOrRemote(string connectionString) {
    
            //Local machine
            IPHostEntry entry = Dns.GetHostByAddress("127.0.0.1");
    
            IPAddress[] addresses = entry.AddressList;
            String[] aliases = entry.Aliases;
            string hostName = entry.HostName;           
    
            if(connectionString.Contains(hostName))
                return true;
    
    
    
            foreach (IPAddress address in addresses) {
                if (connectionString.Contains(address.ToString())) {
                    return true;
                }
            }
    
            foreach (string alias in aliases) {
                if (connectionString.Contains(alias))
                    return true;
            }
    
    
            return false;
        }
    

    Ps: make sure to add a using statement to System.Net namespace.

    0 讨论(0)
  • 2021-01-27 21:10

    Ask SQL using the connection with the statement

    SELECT @@SERVERNAME
    

    then verifiy if this match the name of the client machine with Environment.MachineName, modulo the SQL instance name

    0 讨论(0)
  • 2021-01-27 21:16

    You may check SqlConnection.ConnectionString property to see if it has something like (local) or . in its' server part, but that's not very reliable because of %systemroot%\system32\drivers\etc\hosts' and various other SQL Aliases, wherebyfoo-srv` may well be a local box.

    0 讨论(0)
  • 2021-01-27 21:19

    Easiest way that I am aware of is to check the connectionstring directly to see if it contains either the words localhost, 127.0.0.1, (localhost), "." or the local machine name. Check for starting with since their could be a local named instance of Sql running.

    You can use the System.Environment library to retrieve the current machine name. You can also look at using the ConnectionBuilder library in .Net to retrieve the data without using complete string parsing. Details on this can be found here

    0 讨论(0)
提交回复
热议问题