function::format_ipaddr - Linux


The function::format_ipaddr function accepts an IPv4 or IPv6 address and returns its representation in a user-specified format. It provides flexibility for formatting IP addresses in various contexts, from presentation to technical requirements.


function::format_ipaddr(ipaddr as String, [format: String = "none"]) -> String;


  • format: (Optional) Specifies the output format of the IP address. Available options include:
    • "none": No formatting, returns the original IP address (default).
    • "canonical": Canonicalized IP address in standard format.
    • "short": Shortened representation, omitting leading zeros in IPv4 and colons in IPv6.
    • "dns": DNS-style representation, with IPv4 addresses followed by a period (".") and IPv6 addresses enclosed in square brackets ("[]").
    • "long": Long representation, with leading zeros in IPv4 and colons in IPv6 for improved readability.


# Example 1: Convert IPv4 address to canonical format
function::format_ipaddr("") -> ""

# Example 2: Convert IPv6 address to DNS style
function::format_ipaddr("2001:0db8:85a3:0000:0000:8a2e:0370:7334", "dns") -> "[2001:db8:85a3::8a2e:370:7334]"

# Example 3: Get IPv4 address in short form
function::format_ipaddr("", "short") -> ""

Common Issues

  • Invalid IP address: The provided IP address may be invalid or not in the expected format. Ensure that the input IP address is correct.
  • Unsupported format: The specified format may not be supported by the function. Refer to the available formatting options and ensure proper usage.


function::format_ipaddr can be used in conjunction with other Linux commands for complex tasks involving IP address manipulation:

# Example: Display IP address in different formats
echo "" | function::format_ipaddr - | grep -v none | while read format; do
  function::format_ipaddr "" "$format"

Related Commands

  • function::get_local_ipaddr: Retrieve the local IP address.
  • function::check_ipaddr: Validate an IP address.
  • ipcalc: A tool for complex IPv4 and IPv6 address calculations.