void writeResponse(final DataOutputStream outputStream,
			final Status status, final AddressType addressType,
			final InetAddress boundAddress, final byte[] hostname,
			final int port) throws IOException {

		byte[] safeAddress = null;
		if (boundAddress == null) {
			if (addressType == AddressType.IP_V6) {
				safeAddress = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0 };
			} else {
				safeAddress = new byte[] { 0, 0, 0, 0 };
			}
		} else if (hostname == null) {
			safeAddress = boundAddress.getAddress();
		} else {
			safeAddress = hostname;
		}

		if (status != Status.SUCCEEDED) {
			this.logger.info("Client "
					+ this.getClientSocket().getInetAddress().getHostAddress()
					+ ":" + this.getClientSocket().getPort()
					+ " failed to connected to "
					+ InetAddress.getByAddress(safeAddress).getHostAddress()
					+ ":" + port + ", result 0x"
					+ Integer.toHexString(status.getValue()) + " " + status);
		}

		outputStream.write(SocksImplementation5.PROTOCOL_VERSION);
		outputStream.write(status.getValue());
		outputStream.write(0x00); // reserved

		if (addressType == AddressType.IP_V4) {
			outputStream.write(AddressType.IP_V4.getValue());
			outputStream.write(safeAddress);

		} else if (addressType == AddressType.IP_V6) {
			outputStream.write(AddressType.IP_V6.getValue());
			outputStream.write(safeAddress);

		} else if (addressType == AddressType.DOMAIN) {
			outputStream.write(AddressType.DOMAIN.getValue());
			if (safeAddress == null) {
				outputStream.write(0x00);
			} else {
				outputStream.write(safeAddress.length);
				outputStream.write(safeAddress);
			}
		} else {
			throw new IllegalStateException("Unknown address type: "
					+ addressType);
		}

		outputStream.writeShort(port & 0xFFFF);
		outputStream.flush();
	}