SqlConnection - is remote or local connection?

后端 未结 4 1340
星月不相逢
星月不相逢 2021-01-27 20:20

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?

4条回答
  •  面向向阳花
    2021-01-27 21:09

    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.

提交回复
热议问题