SQL - Query to get server's IP address

前端 未结 10 1430
情深已故
情深已故 2020-11-27 11:35

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

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 11:53

    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.

提交回复
热议问题