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
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
这里的代码会给你 IP 地址;
这将适用于对 SQL2008及更新版本的远程客户端请求。
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
‘ local _ net _ address’的 NULL,以及
‘ <local machine>’将显示在‘ client _ net _ address’中。
“ client _ net _ address”是发出请求的计算机的地址,而“ local _ net _ address”是 SQL 服务器(因此在共享内存连接上为 NULL) ,以及如果某人由于某种原因不能使用服务器的 NetBios 名称或 FQDN,你会给他的地址。
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;
--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;