124

Is there a query in SQL Server 2005 I can use to get the server's IP or name?

Seibar
  • 68,705
  • 38
  • 88
  • 99

13 Answers13

192
SELECT  
   CONNECTIONPROPERTY('net_transport') AS net_transport,
   CONNECTIONPROPERTY('protocol_type') AS protocol_type,
   CONNECTIONPROPERTY('auth_scheme') AS auth_scheme,
   CONNECTIONPROPERTY('local_net_address') AS local_net_address,
   CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
   CONNECTIONPROPERTY('client_net_address') AS client_net_address 

The code here Will give you the IP Address;

This will work for a remote client request to SQL 2008 and newer.

If you have Shared Memory connections allowed, then running above on the server itself will give you

  • "Shared Memory" as the value for 'net_transport', and
  • NULL for 'local_net_address', and
  • '<local machine>' will be shown in 'client_net_address'.

'client_net_address' is the address of the computer that the request originated from, whereas 'local_net_address' would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can't use the server's NetBios name or FQDN for some reason.

I advice strongly against using this answer. Enabling the shell out is a very bad idea on a production SQL Server.

Community
  • 1
  • 1
Jeff Muzzy
  • 1,929
  • 1
  • 11
  • 2
  • 3
    Good answer except I'm getting a negative port number (-15736) for a port that should be 49800. So if negative is it safe to just add 65536? – crokusek Mar 28 '13 at 22:50
  • If someone wants to login remotely into my computer's SQL server, then which IP do I give him ? local_net_address or client_net_address ? – david blaine May 08 '13 at 21:27
  • @rene - was considering it, but the original answer itself is correct (for SQL2008+ and remote connections) so just thought to clarify what the ConnectionProperty params meant. Of course Chris Leonard's answer (dm_exec_connections) also is correct, for the same reasons. If you think my addendum is better off as separate answer than feel free to make it so :) Haven't answered Qs for a while, so policy&rules here might have changed (will go read them up now...) – Martin S. Stoller Feb 25 '15 at 19:53
  • Reason for addenum as per "http://stackoverflow.com/help/editing" : To clarify the meaning of the post (without changing that meaning). – Martin S. Stoller Feb 25 '15 at 20:00
  • 1
    @MartinS.Stoller I edited your addition for readibiity. Please check if I didn't miss anything. – rene Feb 25 '15 at 20:09
  • I ran abobe query and getting below details Shared memory TSQL SQL NULL NULL .. I am getting NULL in local_tcp_port. what should I do? – vikrant rana Aug 07 '19 at 19:49
40

You can get the[hostname]\[instancename] by:

SELECT @@SERVERNAME;

To get only the hostname when you have hostname\instance name format:

SELECT LEFT(ltrim(rtrim(@@ServerName)), Charindex('\', ltrim(rtrim(@@ServerName))) -1)

Alternatively as @GilM pointed out:

SELECT SERVERPROPERTY('MachineName')

You can get the actual IP address using this:

create Procedure sp_get_ip_address (@ip varchar(40) out)
as
begin
Declare @ipLine varchar(200)
Declare @pos int
set nocount on
          set @ip = NULL
          Create table #temp (ipLine varchar(200))
          Insert #temp exec master..xp_cmdshell 'ipconfig'
          select @ipLine = ipLine
          from #temp
          where upper (ipLine) like '%IP ADDRESS%'
          if (isnull (@ipLine,'***') != '***')
          begin 
                set @pos = CharIndex (':',@ipLine,1);
                set @ip = rtrim(ltrim(substring (@ipLine , 
               @pos + 1 ,
                len (@ipLine) - @pos)))
           end 
drop table #temp
set nocount off
end 
go

declare @ip varchar(40)
exec sp_get_ip_address @ip out
print @ip

Source of the SQL script.

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
  • using the xp_cmdshell is a bad idea, the procedure should be removed as it's a security risk allowing access to it as it grants access to the "box" to anyone that can execute it – Walter Verhoeven May 15 '21 at 05:33
25

The server might have multiple IP addresses that it is listening on. If your connection has the VIEW SERVER STATE server permission granted to it, you can run this query to get the address you have connected to SQL Server:

SELECT dec.local_net_address
FROM sys.dm_exec_connections AS dec
WHERE dec.session_id = @@SPID;

This solution does not require you to shell out to the OS via xp_cmdshell, which is a technique that should be disabled (or at least strictly secured) on a production server. It may require you to grant VIEW SERVER STATE to the appropriate login, but that is a far smaller security risk than running xp_cmdshell.

The technique mentioned by GilM for the server name is the preferred one:

SELECT SERVERPROPERTY(N'MachineName');
chris
  • 588
  • 5
  • 16
  • Thanks for this response... I believe this is the true way of determining the server's ip address if you need to verify it from the client's connection side, specially if the client's connection was established with a connection string that contained an SQL alias or named instance as a data source. – Rodolfo G. Apr 12 '12 at 21:09
12

Most solutions for getting the IP address via t-sql fall into these two camps:

  1. Run ipconfig.exe via xp_cmdshell and parse the output

  2. Query DMV sys.dm_exec_connections

I'm not a fan of option #1. Enabling xp_cmdshell has security drawbacks, and there's lots of parsing involved anyway. That's cumbersome. Option #2 is elegant. And it's a pure t-sql solution, which I almost always prefer. Here are two sample queries for option #2:

SELECT c.local_net_address
FROM sys.dm_exec_connections AS c
WHERE c.session_id = @@SPID;

SELECT TOP(1) c.local_net_address
FROM sys.dm_exec_connections AS c
WHERE c.local_net_address IS NOT NULL;

Sometimes, neither of the above queries works, though. Query #1 returns NULL if you're connected over Shared Memory (logged in and running SSMS on the SQL host). Query #2 may return nothing if there are no connections using a non-Shared Memory protocol. This scenario is likely when connected to a newly installed SQL instance. The solution? Force a connection over TCP/IP. To do this, create a new connection in SSMS and use the "tcp:" prefix with the server name. Then re-run either query and you'll get the IP address.

SSMS - Connect to Database Engine

Dave Mason
  • 4,746
  • 2
  • 23
  • 24
  • This will give ipv4.. can we get ipv6? – Shikhil Bhalla Nov 21 '16 at 21:05
  • A clarification may be useful here. Shared memory connections can only be used by clients that are running on the same host as the SQL Server, and there is no need to force them to use TCP to determine where they are running. Option #2 still returns correct information, with `net_transport` = 'Shared memory'` instead of `net_transport = 'TCP'`. When you see that, you know the client is on the SQL Server itself. If you really need the IP address, it is the value in `local_net_address`, but remember that the client itself is not connecting via TCP. – chris May 18 '22 at 15:21
12

--Try this script it works to my needs. Reformat to read it.

SELECT  
SERVERPROPERTY('ComputerNamePhysicalNetBios')  as 'Is_Current_Owner'
    ,SERVERPROPERTY('MachineName')  as 'MachineName'
    ,case when @@ServiceName = 
    Right (@@Servername,len(@@ServiceName)) then @@Servername 
      else @@servername +' \ ' + @@Servicename
      end as '@@Servername \ Servicename',  
    CONNECTIONPROPERTY('net_transport') AS net_transport,
    CONNECTIONPROPERTY('local_tcp_port') AS local_tcp_port,
    dec.local_tcp_port,
    CONNECTIONPROPERTY('local_net_address') AS local_net_address,
    dec.local_net_address as 'dec.local_net_address'
    FROM sys.dm_exec_connections AS dec
    WHERE dec.session_id = @@SPID;
Marco Souza
  • 177
  • 1
  • 3
  • 10
Hank Freeman
  • 1,192
  • 8
  • 7
  • Thanks. Just had to update dec.local_tcp_port as 'dec.local_tcp_port' to use it in a function. Otherwise it complains there are two columns named local_tcp_port. – Steven May 11 '20 at 08:17
9

It's in the @@SERVERNAME variable;

SELECT @@SERVERNAME;
Seibar
  • 68,705
  • 38
  • 88
  • 99
Michał Piaskowski
  • 3,800
  • 2
  • 34
  • 46
7

Please use this query:

SELECT CONNECTIONPROPERTY('local_net_address') AS [IP]

گلی
  • 210
  • 3
  • 13
6
select @@servername
Seibar
  • 68,705
  • 38
  • 88
  • 99
Pseudo Masochist
  • 1,927
  • 14
  • 12
6

you can use command line query and execute in mssql:

exec xp_cmdshell 'ipconfig'
Ranjana Ghimire
  • 1,785
  • 1
  • 12
  • 20
2

A simpler way to get the machine name without the \InstanceName is:

SELECT SERVERPROPERTY('MachineName')
GilM
  • 3,711
  • 17
  • 18
2

I know this is an old post, but perhaps this solution can be usefull when you want to retrieve the IP address and TCP port from a Shared Memory connection (e.g. from a script run in SSMS locally on the server). The key is to open a secondary connection to your SQL Server using OPENROWSET, in which you specify 'tcp:' in your connection string. The rest of the code is merely building dynamic SQL to get around OPENROWSET’s limitation of not being able to take variables as its parameters.

DECLARE @ip_address       varchar(15)
DECLARE @tcp_port         int 
DECLARE @connectionstring nvarchar(max) 
DECLARE @parm_definition  nvarchar(max)
DECLARE @command          nvarchar(max)

SET @connectionstring = N'Server=tcp:' + @@SERVERNAME + ';Trusted_Connection=yes;'
SET @parm_definition  = N'@ip_address_OUT varchar(15) OUTPUT
                        , @tcp_port_OUT   int         OUTPUT';

SET @command          = N'SELECT  @ip_address_OUT = a.local_net_address,
                                  @tcp_port_OUT   = a.local_tcp_port
                          FROM OPENROWSET(''SQLNCLI''
                                 , ''' + @connectionstring + '''
                                 , ''SELECT local_net_address
                                          , local_tcp_port
                                     FROM sys.dm_exec_connections
                                     WHERE session_id = @@spid
                                   '') as a'

EXEC SP_executeSQL @command
                 , @parm_definition
                 , @ip_address_OUT = @ip_address OUTPUT
                 , @tcp_port_OUT   = @tcp_port OUTPUT;


SELECT @ip_address, @tcp_port
Greg Sansom
  • 20,442
  • 6
  • 58
  • 76
0

It is possible to use the host_name() function

select HOST_NAME()
Eralper
  • 6,461
  • 2
  • 21
  • 27
0

If the SQL server instance is on local make sure you have the protocols as follows

enter image description here

If you have SharedMemory protocol enabled:

SELECT ConnectionProperty('local_net_address') AS 'Server IP Address'

returns NULL

SELECT ConnectionProperty('client_net_address') AS 'Client IP Address'

returns < local machine >

After you disable SharedMemory and enable TCP/IP those commands will return the proper IP address

armadillo.mx
  • 934
  • 1
  • 11
  • 17