大网数据广告活动
服务器运维问答

Robust way to resolve a DNS address in a script (IPv4 (A) and IPv6 (AAAA))?

· 52CE 我爱测

I have a domain name in a bash variable ( $TARGET ), and I want to get the IPv4 ( A record) address of it in my bash script (I also want to get the IPv6 AAAA record (if exists)), in a robust manner. i.e. What bash/unix command wi…

问题原文

原帖链接 · Amandasaurus · CC BY-SA 4.0

I have a domain name in a bash variable ($TARGET), and I want to get the IPv4 (A record) address of it in my bash script (I also want to get the IPv6 AAAA record (if exists)), in a robust manner.

i.e. What bash/unix command will: (i) print the IP address (and only the IP address) of the DNS resolution (ii) print nothing to stdout (or non-zero exit) if there is no DNS record for that domain found (iii) allow me to choose to ask for A or AAAA record.

host "$TARGET" prints lots of human readable stuff, and I'm reluctant to parse that.

dig +short looked promising, but in some scenarios, it also prints other warning messages which I do not understand, or care about.

$ dig +short -t A "$TARGET"
;; Warning: Client COOKIE mismatch
1.2.3.4

Debian test/bookworm. Bash v5.2 (installed via apt)

社区高分解答

原帖链接 · JG7 · CC BY-SA 4.0

You are on the right track with dig. You can suppress that particular cookie related error (per the man page). Below, I am also choosing to redirect all errors to /dev/null just in case, as you wanted failures to be silent.

[jg7@comp1 ~]$ TARGET="google.com"

[jg7@comp1 ~]$ dig +short +nobadcookie -t A "$TARGET" @8.8.8.8 2>/dev/null
64.233.177.139
64.233.177.138
64.233.177.101
64.233.177.113
64.233.177.100
64.233.177.102

[jg7@comp1 ~]$ dig +short +nobadcookie -t AAAA "$TARGET" @8.8.8.8 2>/dev/null
2607:f8b0:4002:c08::65
2607:f8b0:4002:c08::8a
2607:f8b0:4002:c08::64
2607:f8b0:4002:c08::71

If this isn't what you are looking for, then let me know.

[EDIT] Used a bash variable so as to be closer to the original question.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2022-09-19)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。