SQL Server Cannot connect to mssql using rust/tiberius

j2cgzkjk  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(146)

I have the following connection-string to connect to local MS-SQL Server version Microsoft SQL Server 2019 (RTM-GDR) (KB5021125) - 15.0.2101.7 (X64)

Data Source=<PC name>\\<instance name>;Initial Catalog=<db name>;User Id=sa;Password=<password>;

It works very well with my C# code.

I also activated both Windows login and SA login

I would like to connect to that database from rust using tiberius and tokio runtime

So I did follow their documentation example code,

I checked multiple combinations of commented lines below, still cannot connect to my db

//let mut config = Config::from_ado_string("<connection string above>").expect("failed");
//let mut config = Config::new();
//config.host("<pc name here>");
//config.host("<pc ip here>");
//config.host("<pc name here>\\<instance name here>");
//config.host("localhost");
//config.host("127.0.0.1");
//config.host("0.0.0.0");
//config.port(<port, usually 1433>);
//config.instance_name("<instance name here>");
//config.database("<db name>");
//config.authentication(AuthMethod::sql_server("sa", "<password here>"));
//config.trust_cert();

let tcp = TcpStream::connect(config.get_addr()).await?;

Experience these type of errors:

Os { code: 10061, kind: ConnectionRefused, message: "No connection could be made because the target machine actively refused it." }

I cannot spot what I am missing there. Guessing that instance name confuses it, rather than directly connecting to host

elcex8rz

elcex8rz1#

Thanks to @AlwaysLearning,
I managed to find my issue.
Issue was on the port side, since it is named instance it is different than 1433 I was using wrong port number
In order to find the exact port for that instance we need to query to SQL Browser using SSRP protocol
Using this simple C# code you can do that

//see this link for documentation
//https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MC-SQLR/%5bMC-SQLR%5d-210625.pdf
var remote = IPEndPoint.Parse("127.0.0.1:1434");
var client = new UdpClient();
client.Connect(remote);
const byte CLNT_UCAST_EX = 03;
client.Send(new byte[1] { CLNT_UCAST_EX });
var buffer = client.Receive(ref remote);
//here buffer becomes like:
//..ServerName;...;InstanceName;...;IsClustered;..;Version;...;tcp;62056;;
// 62056-> is my port number

I used 62056 as port number in my rust code and it worked

相关问题