SQL — запрос для получения IP-адреса сервера
Есть ли запрос в SQL Server 2005, который я могу использовать для получения IP-адреса или имени сервера?
ОТВЕТЫ
Ответ 1
Код здесь даст вам IP-адрес;
Это будет работать для удаленного запроса клиента на SQL 2008 и новее.
Если вы используете Разрешения для общей памяти, то выполнение выше на самом сервере даст вам
- «Общая память» в качестве значения для «net_transport» и
- NULL для ‘local_net_address’ и
- ‘ <local machine> ‘ будет отображаться в ‘client_net_address’.
«client_net_address» — это адрес компьютера, на который был отправлен запрос, тогда как «local_net_address» будет сервером SQL (таким образом, NULL поверх соединений общей памяти) и адресом, который вы бы дали кому-то, если они не могут использовать имя сервера NetBios или полное доменное имя по какой-либо причине.
Я настоятельно советую использовать этот ответ. Включение оболочки — очень плохая идея на производственном SQL Server.
Ответ 2
Вы можете получить имя [hostname]\[instancename]:
Чтобы получить только имя хоста, если у вас есть имя хоста\формат имени экземпляра:
В качестве альтернативы, как @GilM указал:
Вы можете получить фактический IP-адрес, используя это:
Ответ 3
На сервере может быть несколько IP-адресов, которые он прослушивает. Если ваше соединение имеет разрешение сервера просмотра VIEW SERVER STATE, вы можете запустить этот запрос, чтобы получить адрес, который вы подключили к SQL Server:
Это решение не требует, чтобы вы выгружались в ОС через xp_cmdshell, что является методом, который должен быть отключен (или, по крайней мере, строго защищен) на рабочем сервере. Это может потребовать, чтобы вы предоставили статус просмотра VIEW SERVER соответствующему логину, но это гораздо меньший риск для безопасности, чем запуск xp_cmdshell.
Предпочтительная технология, упомянутая GilM для имени сервера:
Ответ 4
Ответ 5
Большинство решений для получения IP-адреса через t-sql попадают в эти два лагеря:
Запустите ipconfig.exe через xp_cmdshell и проанализируйте вывод
Запрос DMV sys.dm_exec_connections
Я не поклонник варианта №1. Включение xp_cmdshell имеет недостатки безопасности, и в этом случае много разбора. Это громоздко. Вариант № 2 элегантен. И это чистое решение t-sql, которое я почти всегда предпочитаю. Вот два примера запросов для опции № 2:
Иногда ни один из вышеперечисленных запросов не работает. Запрос №1 возвращает NULL, если вы подключены к общей памяти (зарегистрировались и запускали SSMS на хосте SQL). Запрос №2 может ничего не возвращать, если нет соединений с использованием протокола без общей памяти. Вероятно, этот сценарий связан с новым экземпляром SQL. Решение? Настройте соединение через TCP/IP. Для этого создайте новое соединение в SSMS и используйте префикс «tcp:» с именем сервера. Затем повторно запустите любой запрос, и вы получите IP-адрес.
Ответ 6
Ответ 7
Более простой способ получить имя машины без имени \InstanceName:
Ответ 8
вы можете использовать запрос командной строки и выполнить в mssql:
Ответ 9
— Попробуйте этот script, он работает для моих нужд. Переформатировать его.
SELECT
SERVERPROPERTY (‘ComputerNamePhysicalNetBios’) как ‘Is_Current_Owner’ , SERVERPROPERTY (‘MachineName’) как ‘MachineName’ , случай, когда @@ServiceName = Right (@@Servername, len (@@ServiceName)), а затем @@Servername else @@servername + ‘\’ + @@Servicename end как ‘@@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 как ‘dec.local_net_address’ FROM sys.dm_exec_connections AS dec WHERE dec.session_id = @@SPID;
Ответ 10
Я знаю, что это старый пост, но, возможно, это решение может быть полезно, когда вы хотите получить IP-адрес и TCP-порт из соединения с общей памятью (например, из script в SSMS локально на сервере). Ключ состоит в том, чтобы открыть дополнительное соединение с вашим SQL Server с помощью OPENROWSET, в котором вы указываете «tcp:» в своей строке подключения. Остальная часть кода просто создает динамический SQL, чтобы обойти ограничение OPENROWSET, неспособное принимать переменные в качестве параметров.
SQL — Query to get server's IP address
Is there a query in SQL Server 2005 I can use to get the server’s IP or name?
13 Answers 13
The code here Will give you the IP Address;
This will work for a remote client request to SQL 2008 and newer.
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
- NULL for ‘local_net_address’, and
- ‘ <local machine> ‘ will be shown in ‘client_net_address’.
‘client_net_address’ is the address of the computer that the request originated from, whereas ‘local_net_address’ would be the SQL server (thus NULL over Shared Memory connections), and the address you would give to someone if they can’t use the server’s NetBios name or FQDN for some reason.
I advice strongly against using this answer. Enabling the shell out is a very bad idea on a production SQL Server.
You can get the[hostname]\[instancename] by:
To get only the hostname when you have hostname\instance name format:
Alternatively as @GilM pointed out:
You can get the actual IP address using this:
The server might have multiple IP addresses that it is listening on. If your connection has the VIEW SERVER STATE server permission granted to it, you can run this query to get the address you have connected to SQL Server:
This solution does not require you to shell out to the OS via xp_cmdshell, which is a technique that should be disabled (or at least strictly secured) on a production server. It may require you to grant VIEW SERVER STATE to the appropriate login, but that is a far smaller security risk than running xp_cmdshell.
The technique mentioned by GilM for the server name is the preferred one:
Most solutions for getting the IP address via t-sql fall into these two camps:
Run ipconfig.exe via xp_cmdshell and parse the output
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:
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.
How to get sql server ip address
edit: when i did ping /? from a command line, i do not see a -o option.
in 2008 and above, you can get it from some of the DMV.s or from some new connection property functions as well:
select local_net_address,* FROM sys.dm_exec_connections
—Requires SQL 2008 +
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’,
ConnectionProperty(‘physical_net_transport’) AS ‘physical_net_transport’
Lowell —help us help you! If you post a question, make sure you include a CREATE TABLE. statement and INSERT INTO. statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!
July 30, 2012 at 1:01 pm
Lowell, just out of curiosity, what would the result set look like on say a clustered SQL Server instance compared to standalone? I don’t have the ability to check this on a clustered instance and I’m curious if the results are different. Perhaps you have a link to a BOL article that explains in more detail?
July 30, 2012 at 1:16 pm
Scott D. Jacobson (7/30/2012)
Lowell, just out of curiosity, what would the result set look like on say a clustered SQL Server instance compared to standalone? I don’t have the ability to check this on a clustered instance and I’m curious if the results are different. Perhaps you have a link to a BOL article that explains in more detail?
Scott you can see a lot of variation in there, as the tcp_ip addresses can be different for each connection, whether you have your server listening to more than one IP address, etc. and of course depending on if you are connecting locally (named pipes makes the ip address for the server return null)
when i connect to my known 2008 cluster, these are the results, which is the clusters IP address of *.235 , and not the node IP (which are *. 230 and *.231, respectively..i seem to remember a witness is on *.232
net_transport protocol_type auth_scheme local_net_address local_tcp_port client_net_address physical_net_transport
TCP TSQL SQL 192.168.0.235 1433 192.168.0.55 NULL
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’,
ConnectionProperty(‘physical_net_transport’) AS ‘physical_net_transport’
Lowell —help us help you! If you post a question, make sure you include a CREATE TABLE. statement and INSERT INTO. statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!
July 30, 2012 at 1:47 pm
Lowell, thank you for the reply to satisfy my curiosity.
nagkarjun1, my apologies. I realize I sort of hijacked your thread
March 17, 2014 at 3:23 am
Can I ask a dumb question..
What will happen if the value of local_net_address is not what the external users are using to connect to the DB?
For example: The server has 2 IPs: lets call it 192.168.1.1 and another 10.0.1.1 (this is the IP everyone should be using to connect to the SQL Server)
Internally and externally via port 1433 connections are successful to 10.0.1.1.
When I run the query listed above if shows 192.168.1.1 as the local_net_address and not 10.0.1.1 as I expected it to.
What would the effect of that be? Would users struggle to connect even if all necessary ports are open? Even if SQL config manager is set up correctly?
I am asking because we are experiencing issues connecting remotely and I am trying to determine if this could be the problem?
One Orange Chip
March 17, 2014 at 4:07 am
Check firewall settings of the remote machine.
—————————————————
«Thare are only 10 types of people in the world:
Those who understand binary, and those who don’t.»
March 17, 2014 at 6:52 am
i would not put too much value in the local ip address; SQL’s configured to listen to multiple ip addresses(including 127.0.0.1), and you can review them in the server configuration tool.
if you are having connectivity issues, it’s going to be at the network layer, and not something you’ll se at the SQL level, i think.
i THINK the ConnectionProperty returns the first IP4 address found in the configuration; if you think it’s relavant, i guess you could remove an ip and put it back, i think that might make it move to the bottom of the list. test that on a developer machine first, obviously.
Lowell —help us help you! If you post a question, make sure you include a CREATE TABLE. statement and INSERT INTO. statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!
Как узнать IP-адрес сервера MySQL от phpmyadmin
У меня есть доступ к моему серверу phpmyadmin. Но как я могу найти адрес mysql Ip из phpmyadmin. Мой веб-сервер и mysql используют разные IP-адреса.
Есть ли способ узнать это?
6 ответов
SQL-запрос SHOW VARIABLES WHERE Variable_name = ‘hostname’ покажет вам имя хоста сервера MySQL, которое вы можете легко решить по его IP-адресу.
SHOW VARIABLES WHERE Variable_name = ‘port’ Позволяет указать номер порта.
Подробнее об этом вы найдете в руководстве по MySQL: 12.4.5.41. SHOW VARIABLES Синтаксис и 5.1.4. Системные переменные сервера
MySQL не заботится о том, на чем IP-адрес. Ближе всего вы можете получить имя хоста: