001/* 002 * Copyright 2015-2018 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.InetAddress; 016import java.net.UnknownHostException; 017 018/** 019 * A resource record representing a internet address. Provides {@link #getInetAddress()}. 020 */ 021public abstract class InternetAddressRR extends Data { 022 023 024 /** 025 * Target IP. 026 */ 027 protected final byte[] ip; 028 029 /** 030 * Cache for the {@link InetAddress} this record presents. 031 */ 032 private InetAddress inetAddress; 033 034 protected InternetAddressRR(byte[] ip) { 035 this.ip = ip; 036 } 037 038 @Override 039 public final void serialize(DataOutputStream dos) throws IOException { 040 dos.write(ip); 041 } 042 043 /** 044 * Allocates a new byte buffer and fills the buffer with the bytes representing the IP address of this resource record. 045 * 046 * @return a new byte buffer containing the bytes of the IP. 047 */ 048 public final byte[] getIp() { 049 return ip.clone(); 050 } 051 052 public final InetAddress getInetAddress() { 053 InetAddress i = this.inetAddress; 054 if (i == null) { 055 try { 056 i = InetAddress.getByAddress(ip); 057 } catch (UnknownHostException e) { 058 throw new IllegalStateException(e); 059 } 060 this.inetAddress = i; 061 } 062 return i; 063 } 064 065}