Friday, September 22, 2006

SQL Server: How to get the server's IP Address using T-SQL

Someone asked this on a newsgroup, and my answer: If you have admin rights on the server, you can use xp_cmdshell to run a command line application, grab the results and parse them.
CREATE TABLE #temp1
(t varchar(3000))

insert into #temp1
exec xp_cmdshell 'ipconfig'
DECLARE @t1 varchar(300)

-- subject to localisation
SET @t1 = (SELECT top 1 t from #temp1
where t like '%IP Address%' order by t DESC)

declare @len int
set @Len = CHARINDEX(':', @t1)

SELECT TOP 1 LTRIM(RTRIM(SUBSTRING(@t1, @Len+1, LEN(@T1)))) as T

drop table #temp1