如何从SQL Server数据库获取客户端IP地址

时间:2012-10-08 13:01:49

标签: sql-server

假设我有三台机器。一个是服务器,另外两个是客户端。服务器上已安装SQL数据库,另外两台计算机上安装了SQL Server客户端。因此,人们可以从客户端计算机连接到SQL Server服务器数据库。

现在我想,每当有人在桌面上进行DML操作时,触发器就会触发,并且从该触发器开始,用户的客户端机器IP地址将存储在另一个表中。所以我搜索好,发现了一个脚本:

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

但是上面的脚本给出了安装数据库的服务器IP地址。我不是在寻找这个剧本。我有另一个脚本工作正常。脚本是:

CREATE FUNCTION [dbo].[GetCurrentIP] ()
RETURNS varchar(255)
AS
BEGIN
    DECLARE @IP_Address varchar(255);

    SELECT @IP_Address = client_net_address
    FROM sys.dm_exec_connections
    WHERE Session_id = @@SPID;

    Return @IP_Address;
END

SELECT dbo.GetCurrentIP()

更多脚本


DECLARE @host varchar(255)
SET @host = host_name()

CREATE TABLE #Results (
Results varchar(255)
)

DECLARE @cmd varchar(260)
SET @cmd = 'ping ' + @host

INSERT INTO #Results
EXEC master..xp_cmdshell @cmd

SELECT Replace(Left(Results, CharIndex(']', Results)), 'Pinging ', '') As [client]
 , host_name() As [host_name()]
FROM   #Results
WHERE  Results LIKE 'Pinging%'

DROP TABLE #Results

- *********************************************

-- DROP trigger and/or table if they exist
IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'TR' AND name = 'myTable_InsertUpdate') BEGIN
    DROP TRIGGER myTable_InsertUpdate
END
IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' AND name = 'myTable') BEGIN
    DROP TABLE myTable
END

-- Create out table; note the audit fields
CREATE TABLE myTable (
id int PRIMARY KEY NOT NULL IDENTITY(1,1)
, field1           char(1)
, changed_by_ip    char(15)
, changed_by_host  char(15)
, datetime_changed datetime
)
GO

-- Create trigger for update and insert
CREATE TRIGGER myTable_InsertUpdate
ON  myTable
FOR insert, update
AS
DECLARE @ipLine varchar(255)
DECLARE @pos    int
DECLARE @ip     char(15)

-- Temporary table creation
CREATE TABLE #ip (
ipLine varchar(255)
)

-- Insert the return of ipconfig into the temp table
INSERT #ip EXEC master..xp_cmdshell 'ipconfig'

-- Find the line which contains the IP address and assign it to a variable
SET @ipLine = (
SELECT ipLine
FROM   #ip
WHERE  ipLine LIKE '%IP Address%'
)

-- If the IP address is known
IF Coalesce(@ipLine, '***') <> '***' BEGIN
    --Find the index of the colon from the END of the string
    SET @pos = CharIndex(':', Reverse(@ipLine), 1) - 1
    --Trim the IP off the end of the string
    SET @ip =  Right(@ipLine, @pos)
    --Remove any trailing or leading white space
    SET @ip  = RTrim(LTrim(@ip))
END

-- Drop the temp table
DROP TABLE #ip

-- Update the audit fields based on the value being updated
UPDATE myTable
SET    changed_by_ip  = @ip
   , datetime_changed = GetDate()
   , changed_by_host  = host_name()
WHERE  id IN (SELECT id FROM inserted)
GO

-- Insert some test values
INSERT INTO myTable (field1) VALUES ('a')
INSERT INTO myTable (field1) VALUES ('a')

-- Display initial values
SELECT * FROM myTable

-- Update one of the fields
UPDATE myTable
SET    field1 = 'b'
WHERE  id = 2

-- Display changed values.
SELECT * FROM myTable

-- Notice the change in datetime_changed where id = 2
GO

-- And finally; clean up after ourselves
DROP TRIGGER myTable_InsertUpdate
DROP TABLE myTable

这适用于我安装的SQL Server 2000SQL Server 2005

  1. 我可以从触发器调用此GetCurrentIP()函数吗?

  2. GetCurrentIP()函数是否兼容所有SQL Server版本?例如,SQL Server 2000

  3. 如果任何用户连接到数据库并通过第三方应用程序(如自定义应用程序)执行DML操作,此脚本是否可以获取客户端IP地址?

1 个答案:

答案 0 :(得分:0)

大问题:)但答案非常简短。

  
      
  1. 我可以从触发器调用此GetCurrentIP()函数吗?
  2.   

是。您可以直接在触发器中使用其中的代码而不是此功能。

  
      
  1. GetCurrentIP()函数是否兼容所有SQL Server版本?例如,SQL Server 2000?
  2.   

没有。仅适用于SQL Server 2005及更高版本。因为sys.dm_exec_sessions在SQL Server 2000中不可用。对于SQL Server,您将不得不采用一些不同的技术

  
      
  1. 如果任何用户连接到数据库并通过第三方应用程序(如自定义应用程序)执行DML操作,此脚本是否可以获取客户端IP地址?
  2.   

是。客户端应用程序是客户端应用程序,无论是第三方应用程序还是自制应用程序:) SQL Server无法区分。