package talk;

import java.io.*;
import java.net.*;

/**
   A Java representation of the sockaddr_in C structure, with methods
   to read and write it to a DataStream.  size == 16 bytes

   For internal use in TalkTransact and TalkServer.
 */
public class SockaddrIn {
  static final int length = 16;
  static final int AF_UNIX = 1;
  static final int AF_INET = 2;

  public SockaddrIn() {
    port = 0;
    try {
      addr = InetAddress.getByName("0.0.0.0");
    } catch (UnknownHostException e) {
      throw new TalkdException(e.toString());
    }
  }
  SockaddrIn(int port, InetAddress addr) {
    this.port = port;
    this.addr = addr;
  }
  
  short family = AF_INET;
  int port;
  InetAddress addr;

  public void readData(DataInputStream is) throws IOException {
    family = is.readShort();
    port = is.readUnsignedShort();
    String addrStr =
      is.readUnsignedByte() + "." +
      is.readUnsignedByte() + "." +
      is.readUnsignedByte() + "." +
      is.readUnsignedByte();
    addr = InetAddress.getByName(addrStr);
    is.skipBytes(8);
  }

  public void writeData(DataOutputStream os) throws IOException {
    os.writeShort(family);
    os.writeShort(port);
    os.write(addr.getAddress(), 0, 4);
    for (int i = 0; i < 8; i++)	// padding
      os.writeByte(0);
  }

  public String toString() {
    return "SockaddrIn@"+Integer.toHexString(hashCode())+":\n" +
      " family = "+family+"\n"+
      " port = "+port+"\n"+
      " addr = "+addr;
  }
}

