You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Erlang技术问题:如何通过主机名获取IP地址

Resolving Hostname to IP Address in Erlang

Hey there! Let's sort this out for you. The net_adm:dns_hostname/1 function you're using only resolves the hostname to its canonical fully qualified domain name (FQDN)—it doesn't return the IP address directly. Here are the go-to methods in Erlang to get the IP you need:

1. Use inet:getaddr/2 for a single IP

This is the standard function for resolving a hostname to an IPv4 or IPv6 address. You need to specify the address family as the second argument:

% Get IPv4 address
inet:getaddr("testhost.fritz.box", inet).
% Example return: {ok, {192,168,1,105}}

% Get IPv6 address (if your network supports it)
inet:getaddr("testhost.fritz.box", inet6).

If the hostname can't be found, you'll get an error like {error, nxdomain} (no such domain) or {error, timeout} if the DNS request takes too long.

2. Get all associated IPs with inet_res:getaddrs/2

If your hostname maps to multiple IP addresses (common for some servers), this function returns a list of all resolved addresses:

inet_res:getaddrs("testhost.fritz.box", inet).
% Example return: {ok, [{192,168,1,105}, {192,168,1,106}]}

3. Convert IP tuple to a human-readable string (optional)

If you need the IP as a string instead of an Erlang tuple, use inet:ntoa/1 to convert it:

{ok, IpTuple} = inet:getaddr("testhost.fritz.box", inet),
inet:ntoa(IpTuple).
% Returns "192.168.1.105"

Just to clear up the confusion: net_adm:dns_hostname/1 is designed to resolve hostname aliases to their official FQDN, not to retrieve IP addresses. That's why it only returned the hostname you passed in (or its canonical version). The inet and inet_res modules are the right tools for IP resolution tasks.

内容的提问来源于stack exchange,提问作者david

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:27:18