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?
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.
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.
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
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