IPAddress Java Library

repository·master·Indexed 19 days ago

https://github.com/seancfoley/ipaddress

A comprehensive Java library for handling IPv4 and IPv6 addresses and subnets. It supports CIDR manipulation, address ranges, containment checks, longest prefix matching, and address tries. The library provides utilities for parsing IP and subnet strings via IPAddressString, handling hostnames via the HostName class, and managing MAC address formats through MACAddressParseData.

Tokens
2.1K
Snippets
6
Records
9
Agent score
18%

What's inside ipaddress

  1. Install IPAddress via Maven

    master

    To use IPAddress in your Java project, add the following dependency to your Maven configuration. The library is available in Maven Central.

    Maven Coordinates:

    • Group ID: com.github.seancfoley
    • Artifact ID: ipaddress

    Note: For OSGI environments, the bundle ID is com.github.seancfoley.ipaddress (available since version 5.3.1).

    <!-- Example Maven dependency structure -->
    <dependency>
        <groupId>com.github.seancfoley</groupId>
        <artifactId>ipaddress</artifactId>
        <version>5.6.2</version>
    </dependency>
  2. Understand IPAddressParseData and AddressParseData

    master

    The IPAddressParseData and AddressParseData classes are internal data structures used by the library to store information collected during the parsing of an IP address string. This data is subsequently used to construct concrete IPv4Address or IPv6Address objects.

    Key Abstractions

    • AddressParseData: The base class that maintains segment-level data, including segment values (lower and upper boundaries), radix (base), bit size, and flags (e.g., whether a segment is a wildcard or part of a range).
    • IPAddressParseData: Extends AddressParseData to include IP-specific metadata such as the IP version (IPv4 vs IPv6), whether the address is zoned (e.g., IPv6 scope IDs), whether it contains a prefix/port qualifier, and support for mixed IPv6/IPv4 addresses.
    • MACAddressParseData: Extends AddressParseData specifically for MAC addresses, tracking the format (e.g., DASHED, COLON_DELIMITED, DOTTED) and whether it is an extended 64-bit identifier.
  3. Parse IP address or subnet strings in Groovy

    master

    In Groovy, you can parse IP strings using IPAddressString. You can use standard try-catch blocks for error handling or check for null when using the .getAddress() method.

    // Using exceptions
    def addressStr = new IPAddressString('a:b:c:d:e:f:1.2.3.4')
    try {
    	def address = addressStr.toAddress()
    } catch (AddressStringException e) {
    	// handle error
    }
    
    // Checking for null
    def subnetStr = new IPAddressString('108.30-31.*.*')
    def subnet = subnetStr.getAddress()
    if(subnet != null) {
    	// use address
    }
  4. Parse IP address or subnet strings in Kotlin

    master

    In Kotlin, you can parse IP strings using IPAddressString. You can either use explicit exception handling for invalid formats or use nullable types for a more idiomatic Kotlin approach.

    Using Exceptions:

    val ipv6Str = "a:b:c:d::a:b/64"
    try {
    	val ipv6Addr = IPAddressString(ipv6Str).toAddress()
    } catch(e: AddressStringException) {
    	// handle error
    }

    Using Nullable Types:

    val ipv6v4Str = "a:b:c:d:e:f:1.2.3.4/112"
    val ipv6v4AddressStr = IPAddressString(ipv6v4Str)
    val ipAddr: IPAddress? = ipv6v4AddressStr.address
    // ipAddr will be null if the string is invalid
    val ipv6Str = "a:b:c:d::a:b/64"
    try {
    	val ipv6AddressStr = IPAddressString(ipv6Str)
    	val ipv6Addr = ipv6AddressStr.toAddress()
    	// use address
    	println(ipv6Addr) // a:b:c:d::a:b/64
    } catch(e: AddressStringException) {
    	println(e.message)
    }
  5. Parse IP address or subnet strings in Scala

    master

    In Scala, use IPAddressString wrapped in a Try block to handle potential AddressStringException errors safely using pattern matching.

    import scala.util.{Failure, Success, Try}
    
    val addressStr = new IPAddressString("a:b:c:d::/64")
    Try(addressStr.toAddress) match {
        case Success(userInfo) =>
            // use address
        case Failure(exception: AddressStringException) =>
            // handle improperly formatted address string
    }
  6. Parse IP address or subnet strings in Java

    master

    Use IPAddressString to convert string representations of IP addresses or subnets (including CIDR notation) into IPAddress objects. This method throws an AddressStringException if the string format is invalid.

    String ipv6Str = "::/64";
    String ipv4Str = "1.2.255.4/255.255.0.0";
    try {
    	IPAddress ipv6Address = new IPAddressString(ipv6Str).toAddress();
    	IPAddress ipv4Address = new IPAddressString(ipv4Str).toAddress();
        // use addresses
    } catch (AddressStringException e) {
    	// handle improperly formatted address string
    }
  7. Parse host name strings in Java

    master

    Use the HostName class to handle strings that may contain hostnames, IP addresses, ports, or service names.

    Key methods:

    • asInetSocketAddress(): Returns an InetSocketAddress.
    • asInetSocketAddress(Function<String, Integer> serviceMapper): Allows mapping service names to specific port numbers.
    • asAddress(): Returns the IPAddress without performing DNS resolution.
    • toAddress(): Returns the IPAddress, performing DNS resolution if necessary.

    Throws HostNameException or UnknownHostException on failure.

    String hostPortStr = "[a:b:c:d:e:f:a:b]:8080";
    String hostServiceStr = "a.b.com:service";
    String hostAddressStr = "1.2.3.4";
    String dnsStr = "a.b.com";
    try {
    	HostName host = new HostName(hostPortStr);
    	InetSocketAddress socketAddress = host.asInetSocketAddress();
    	        
    	host = new HostName(hostServiceStr);
    	socketAddress = host.asInetSocketAddress(
    		service -> service.equals("service") ? 100 : null);
    	        
    	host = new HostName(hostAddressStr);
    	IPAddress address = host.asAddress(); // does not resolve
    	        
    	host = new HostName(dnsStr);
    	address = host.toAddress(); // resolves if necessary
    	        
    } catch (HostNameException | UnknownHostException e) {
    	// handle improperly formatted host name or address string
    }
  8. Identify IP address properties via IPAddressParseData

    master

    When working with the parsing internals, IPAddressParseData provides methods to inspect the characteristics of the parsed string:

    • Version Detection: Use isProvidingIPv4() and isProvidingIPv6() to determine the detected IP version.
    • Zoning and Qualifiers: Use isZoned() to check for zone information and getQualifier() to retrieve the ParsedHostIdentifierStringQualifier.
    • Compression: Use isCompressed() to check if the address uses compression (like :: in IPv6).
    • Special Formats: Use isProvidingBase85IPv6() to detect Base85 encoded IPv6 addresses or isProvidingMixedIPv6() for mixed IPv4/IPv6 formats.
  9. Identify MAC address formats via MACAddressParseData

    master

    For MAC address parsing, MACAddressParseData allows you to inspect the detected format and structure:

    • getFormat(): Returns a MACFormat enum indicating the separator used (e.g., DASHED, COLON_DELIMITED, DOTTED, or SPACE_DELIMITED).
    • isDoubleSegment(): Indicates if the MAC address uses double segments.
    • isExtended(): Indicates if the address is an extended 64-bit identifier.