// Copyright 1997 The Open Group Research Institute.  All rights reserved.

package krb5.lib;

import java.io.*;
import java.net.*;

/**
 * UDP client
 */
public class UDPClient {

	/**
	 * Inet address
	 */
	InetAddress iaddr;

	/**
	 * Port
	 */
	int iport;

	/**
	 * Buffer size
	 */
	int bufSize = 65507;

	/**
	 * Datagram socket
	 */
	DatagramSocket dgSocket;

	/**
	 * Datagram packet
	 */
	DatagramPacket dgPacketIn;

	/**
	 * Class constructor
	 *
	 * @param newIAddr is of type InetAddress
	 * @param port is of type int
	 * @exception SocketException an exception
	 * @java.net.InetAddress
	 * @java.net.SocketException
	 */
	public UDPClient(InetAddress newIAddr, int port)
		throws SocketException {
		iaddr = newIAddr;
		iport = port;
		dgSocket = new DatagramSocket();
	}

	/**
	 * Class constructor
	 *
	 * @param hostname is of type String
	 * @param port is of type int
	 * @exception UnknownHostException an exception
	 * @exception SocketException an exception
	 * @java.net.UnknownHostException
	 * @java.net.SocketException
	 */
	public UDPClient(String hostname, int port)
		throws UnknownHostException, SocketException {
		iaddr = InetAddress.getByName(hostname);
		iport = port;
		dgSocket = new DatagramSocket();
	}

	/**
	 * Sets the buffer size
	 *
	 * @param newBufSize is of type int
	 */
	public void setBufSize(int newBufSize) {
		bufSize = newBufSize;
	}

	/**
	 * Returns inet address
	 *
	 * @return InetAddress is a result
	 * @java.net.InetAddress
	 */
	public InetAddress getInetAddress() {
		if (dgPacketIn != null)
			return dgPacketIn.getAddress();
		return null;
	}

	/**
	 * Sends the data
	 *
	 * @param data is of type byte[]
	 * @exception IOException an exception
	 * @see java.io.IOException
	 */
	public void send(byte[] data) throws IOException {
		DatagramPacket dgPacketOut = new DatagramPacket(data, data.length,
			iaddr, iport);
		dgSocket.send(dgPacketOut);
	}

	/**
	 * Recives
	 *
	 * @return byte[] is a result
	 * @exception IOException an exception
	 * @see java.io.IOException
	 */
	public byte[] receive() throws IOException {
		byte ibuf[] = new byte[bufSize];
		dgPacketIn = new DatagramPacket(ibuf, ibuf.length);
        //XXX this ones for you Netscape...
        try {
            dgSocket.receive(dgPacketIn);
        }
        catch (SocketException e) {
            dgSocket.receive(dgPacketIn);
        }
		byte[] data = new byte[dgPacketIn.getLength()];
		System.arraycopy(dgPacketIn.getData(), 0, data, 0,
			dgPacketIn.getLength());
		return data;
	}

}