SQL statement query SQL server server name and IP address

Time:2021-4-7

Get server name:


SELECT SERVERPROPERTY('MachineName')
select @@SERVERNAME
select HOST_NAME()

Get IP address can use XP_ Cmdshell executes ipconfig command:

--Open XP_ cmdshell 
exec sp_configure'show advanced options', 1 
reconfigure with override 
exec sp_configure'xp_cmdshell', 1 
reconfigure with override 
exec sp_configure'show advanced options', 0 
reconfigure with override 
go 
 
begin 
declare @ipline varchar(200) 
declare @pos int 
declare @ip varchar(40) 
set nocount on 
set @ip = null 
  if object_id('tempdb..#temp') is not null drop table #temp 
  create table #temp(ipline varchar(200)) 
  insert #temp exec master..xp_cmdshell'ipconfig' 
  select @ipline = ipline 
  from #temp 
  Where upper (ipline) like% IPv4 address 
  if @ipline is not null 
  begin 
    set @pos = charindex(':',@ipline,1); 
    set @ip = rtrim(ltrim(substring(@ipline , 
    @pos + 1 , 
    len(@ipline) - @pos))) 
  end 
  select distinct(rtrim(ltrim(substring(@ipline , 
  @pos + 1 , 
  len(@ipline) - @pos)))) as ipaddress from #temp 
drop table #temp 
 
 
set nocount off 
end 
go

But in many cases, XP is not allowed because of security problems_ Cmdshell, you can query SYS.DM_ EXEC_ CONNECTIONS :


SELECT SERVERNAME = CONVERT(NVARCHAR(128),SERVERPROPERTY('SERVERNAME')) 
,LOCAL_NET_ADDRESS AS 'IPAddressOfSQLServer'
,CLIENT_NET_ADDRESS AS 'ClientIPAddress'
 FROM SYS.DM_EXEC_CONNECTIONS WHERE SESSION_ID = @@SPID