function::format_ipaddr - Linux


Overview

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.

Syntax

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

Options/Flags

  • 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.

Examples

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

# 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("192.0.2.1", "short") -> "192.0.2.1"

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.

Integration

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 "192.168.1.1" | function::format_ipaddr - | grep -v none | while read format; do
  function::format_ipaddr "192.168.1.1" "$format"
done

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.