Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you parse the SRV record's port from a dig result?

Tags:

bash

port

dns

dig

I'm parsing the output of dig like this to get the port of an SRV record.

export SERVER_DNS_NAME=myserver
echo "SERVER_DNS_NAME: " $SERVER_DNS_NAME
echo "dig: " $(dig +noall +answer $SERVER_DNS_NAME SRV )
echo "port old: " $(dig +noall +answer $SERVER_DNS_NAME SRV | cut -d ' ' -f 6)
SERVER_DIG_RESULT=$(dig +noall +answer $SERVER_DNS_NAME SRV )
echo "SERVER_DIG_RESULT: " $SERVER_DIG_RESULT
SERVER_STRING_ARRAY=($SERVER_DIG_RESULT)
for i in "${SERVER_STRING_ARRAY[@]}"
do
  :
  echo $i
done
SERVER_PORT=${SERVER_STRING_ARRAY[6]}
echo "server port new: " $SERVER_PORT
if [ -z $SERVER_PORT ]; then
  echo "invalid port"
  exit 1
fi
until nc -z $SERVER_DNS_NAME $SERVER_PORT
... do something

My problem is that sometimes the port is at array item 6, sometimes 7.

My question is: How do you reliably parse the port from a dig result?

like image 928
hawkeye Avatar asked Mar 11 '23 12:03

hawkeye


2 Answers

Use the +short option to dig which will give you the most abbreviated output which is then trivially parsed:

% dig +short _xmpp-client._tcp.jabber.org. SRV
31 30 5222 hermes2v6.jabber.org.
30 30 5222 hermes2.jabber.org.
like image 144
Alnitak Avatar answered Apr 04 '23 17:04

Alnitak


You may like this one too:

host -t SRV mySRVdomain.local                                           
# mySRVdomain.local has SRV record 1 1 2368 e04dc24b-96c6-4b52-8356-42be0d34e7bb.mySRVdomain.local.


# get it as host:port
host -t SRV mySRVdomain.local | sed -r 's/.+ ([^ ]+) ([^ ]+)\.$/\2:\1/g'

# This will print: e04dc24b-96c6-4b52-8356-42be0d34e7bb.mySRVdomain.local:2368
# which is the first real URL with PORT

It maybe not exactly the same that you need, but you can get the idea

like image 28
Kostanos Avatar answered Apr 04 '23 15:04

Kostanos