Reputation: 33
In my code, I have to get the TCP port of the source port I'm connection from. I only have a SqlConnection(System.Data.SqlClient.SqlConnection)
object, what is the best way to get the port from my SqlConnection object in C#?
Upvotes: 0
Views: 831
Reputation: 33
Thanks for your answer, but they are not the answer I want.
Actually I want the port I'm connection from. for example: With netstat I get connection information as following: TCP 10.11.12.13:3055 9.10.11.12:1433 ESTABLSHED
I want to get port '3055' from SqlConnecton object.
Upvotes: 0
Reputation: 43596
You could use SqlConnection.ConnectionString
and grab the Port from the DataSource
object as this should be at the end of the DataSource
seperated by comma (myDatabaseServer\Insatnce,1433")
Example:
int port = int.Parse(sqlCon.ConnectionString.DataSource.Split(',').Last());
Don't forget to add error handling :)
Upvotes: 1
Reputation: 2674
The SqlConnection.ConnectionString may contain the port in "Data Source". Have you tried running in "Debug" mode to trigger break points in your code? You should be able to inspect all the properties for that SqlConnection.
Not sure exactly what SqlConnection.RetrieveStatistics() returns, but you could inspect its return values as well.
Upvotes: 0