SqlConnection - is remote or local connection?

谁都会走 提交于 2019-12-02 18:35:06

问题


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?


回答1:


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




回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/886543/sqlconnection-is-remote-or-local-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!