views:

378

answers:

4

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  A: 

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.

Galilyou
Well, it may be "127.0.0.1", "localhost", "HOME" or "WORK" etc and all of them are aliases of local machine :(
avishnyakov
A: 

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, whereby foo-srv` may well be a local box.

Anton Gogolev
A: 

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

Diago
I think it is good solution for me.Thank you, Diago.
avishnyakov
+2  A: 

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

Giulio Vian
And what about mssql server alias? - http://msdn.microsoft.com/en-us/library/ms188635.aspxDoes your way work if I use alias?
avishnyakov
Should work: @@servername is set at setup-time and is the name of the machine/cluster.Be aware that it represents a cluster you may only access cluster disks (e.g. c$ is not available)
Giulio Vian
I check it and it works nice. Really good solution!
avishnyakov