#include <string>
#include <sys/socket.h>
#include <protocols/talkd.h>
#include <netinet/in.h>
#include <fstream>
#include <arpa/inet.h>

void dump_ctl_msg(istream& inf)
{
  CTL_MSG m;
  inf.read((char*)&m, sizeof(m));
  if (!inf) {
    cerr << "failed to read ctl msg" << endl;
    return;
  }

  const sockaddr_in& addr = *((sockaddr_in*)&m.addr);
  const sockaddr_in& ctl_addr = *((sockaddr_in*)&m.ctl_addr);
  string a = inet_ntoa(addr.sin_addr);
  string b = inet_ntoa(ctl_addr.sin_addr);
  
  cout << "version = " << (int)m.vers << endl
       << "type = " << (int)m.type << endl
       << "answer = " << (int)m.answer << endl
       << "id_num = " << ntohl(m.id_num) << endl
    
       << "addr = family " << ntohs(addr.sin_family) << ", "
       << "port " << ntohs(addr.sin_port) << ", "
       << "address " << a << endl

       << "ctl_addr = family " << ntohs(ctl_addr.sin_family) << ", "
       << "port " << ntohs(ctl_addr.sin_port) << ", "
       << "address " << b << endl

       << "pid = " << ntohl(m.pid) << endl
       << "l_name = " << m.l_name << endl
       << "r_name = " << m.r_name << endl
       << "r_tty = " << m.r_tty << endl;
}
    
int main(int argc, char **argv)
{
  if (argc == 1)
    dump_ctl_msg(cin);
  else {
    const char *fname = argv[1];
    ifstream inf(fname);
    if (!inf) {
      cerr << "Failed to open " << fname << endl;
      return 1;
    }
    dump_ctl_msg(inf);
  }

  return 0;
}
