Thursday, 8 July 2010

A T-SQL query to get the TCP ports used by the current sessions

The other day I was having some difficulty getting to a Sql Server in a different subnet, so I thought the issue could be in some firewall/gateway/proxy/other-chap-in-the-middle.

As part of my investigation, I quickly wrote this bit of T-SQL, which should retrieve, with other useful stuff, also the TCP ports used by the various sessions connected to a Sql Server:

SELECT
connections.session_id as [Session Id],
connections.net_transport as [Net transport protocol],
connections.local_net_address + ':' + cast (connections.local_tcp_port as varchar) as [Server net address and port],
connections.client_net_address + ':' + cast (connections.client_tcp_port as varchar) as [Client net address and port],
sessions.login_name as [Login name],
sessions.host_name as [Host name],
sessions.program_name as [Application name]
FROM sys.dm_exec_connections AS connections
INNER JOIN sys.dm_exec_sessions AS sessions
ON connections.session_id = sessions.session_id
ORDER BY
connections.net_transport,
connections.local_net_address,
connections.local_tcp_port

It may be useful to know if a non standard port is being used (the standard port is 1433), as firewalls or other stuff in the middle may not like those.

This is i.e. the result of such a query on a Dev Sql Server:

Session Id,Net transport protocol,Server net address and port,Client net address and port,Login name,Host name,Application name
52 Shared memory NULL NULL NT AUTHORITY\SYSTEM CERES Report Server
54 Shared memory NULL NULL NT AUTHORITY\SYSTEM CERES SQLAgent - Generic Refresher
57 Shared memory NULL NULL NT AUTHORITY\SYSTEM CERES Report Server
51 TCP 10.25.81.63:1433 10.25.81.0:2628 sa APOLLO Microsoft SQL Server Management Studio - Query
55 TCP 10.25.81.63:1433 10.25.81.64:3384 sa MITRA Microsoft SQL Server Management Studio - Query
56 TCP 10.25.81.63:1433 10.25.81.0:2844 sa APOLLO Microsoft SQL Server Management Studio
53 TCP 10.25.81.63:1433 10.25.81.64:3363 sa MITRA Microsoft SQL Server Management Studio

No comments: