SqlConnection - remote or local connection?

How can I detect this local connection (localhost or 127.0.0.1) or this remote connection (another computer in the local scope) if I have a SqlConnection object?

0


a source to share


4 answers


The easiest way I know of is to check the connection string directly to see if it contains the words localhost, 127.0.0.1, (localhost), "." or the name of the local machine. Check where to start as theirs might be a local named Sql instance.



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

0


a source


Query SQL using statement connection

SELECT @@SERVERNAME

      



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

+2


a source


You can get the connection string from objjct SqlConnection.

string s = connection.ConnectionString;

      

and check the datasource or server element of that row.

Edit: Given code example.

I think this feature should work (not tested anyway).

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 the System.Net namespace.

+1


a source


You can check the property SqlConnection.ConnectionString

to see if it has something like (local)

or .

in its part server

, but this is not very reliable because of %systemroot%\system32\drivers\etc\hosts' and various other SQL Aliases, whereby

foo-srv` it could very well be a local block.

0


a source







All Articles