user656
user656

Reputation: 347

SqlConnection - is remote or local connection?

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?

Upvotes: 0

Views: 1115

Answers (4)

Giulio Vian
Giulio Vian

Reputation: 8343

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

Upvotes: 2

Ahmed
Ahmed

Reputation: 11403

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.

Upvotes: 1

BinaryMisfit
BinaryMisfit

Reputation: 30549

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

Upvotes: 0

Anton Gogolev
Anton Gogolev

Reputation: 115829

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.

Upvotes: 0

Related Questions