001/*
002 * Copyright 2015-2020 the original author or authors
003 *
004 * This software is licensed under the Apache License, Version 2.0,
005 * the GNU Lesser General Public License version 2 or later ("LGPL")
006 * and the WTFPL.
007 * You may choose either license to govern your use of this software only
008 * upon the condition that you accept all of the terms of either
009 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL.
010 */
011package org.minidns.record;
012
013import java.io.DataOutputStream;
014import java.io.IOException;
015import java.net.Inet4Address;
016import java.net.Inet6Address;
017import java.net.InetAddress;
018import java.net.UnknownHostException;
019
020/**
021 * A resource record representing a internet address. Provides {@link #getInetAddress()}.
022 */
023public abstract class InternetAddressRR<IA extends InetAddress> extends Data {
024
025
026    /**
027     * Target IP.
028     */
029    protected final byte[] ip;
030
031    /**
032     * Cache for the {@link InetAddress} this record presents.
033     */
034    private transient IA inetAddress;
035
036    protected InternetAddressRR(byte[] ip) {
037        this.ip = ip;
038    }
039
040    protected InternetAddressRR(IA inetAddress) {
041        this(inetAddress.getAddress());
042        this.inetAddress = inetAddress;
043    }
044
045    @Override
046    public final void serialize(DataOutputStream dos) throws IOException {
047        dos.write(ip);
048    }
049
050    /**
051     * Allocates a new byte buffer and fills the buffer with the bytes representing the IP address of this resource record.
052     *
053     * @return a new byte buffer containing the bytes of the IP.
054     */
055    public final byte[] getIp() {
056        return ip.clone();
057    }
058
059    @SuppressWarnings("unchecked")
060    public final IA getInetAddress() {
061        if (inetAddress == null) {
062            try {
063                inetAddress = (IA) InetAddress.getByAddress(ip);
064            } catch (UnknownHostException e) {
065                throw new IllegalStateException(e);
066            }
067        }
068        return inetAddress;
069    }
070
071    public static InternetAddressRR<? extends InetAddress> from(InetAddress inetAddress) {
072        if (inetAddress instanceof Inet4Address) {
073            return new A((Inet4Address) inetAddress);
074        }
075
076        return new AAAA((Inet6Address) inetAddress);
077    }
078}