/************************************************************
Whois Client für ch Domains
Programmed by c-worker
www.c-worker.ch

*************************************************************/

#include <windows.h>
#include <winsock2.h>
#include <iostream.h>
#include <time.h>

// whois.nic.ch
#define WHOIS_SERVER_IP           "130.59.1.81"
#define WHOIS_PORT                43

// Prototypen
long WinsockStartup();
unsigned long WINAPI RecvData(void *s);

int main()
{
  long rc;
  SOCKET whoisSocket;
  SOCKADDR_IN whoisAddr;

  char recvBuf[10000];
  char sendBuf[256];

  int sendSize=0;


  cout << "Domain Name: " << endl;
  cin >> sendBuf;

  for(sendSize=0;sendSize<256;sendSize++)
  {
    if(sendBuf[sendSize] == '\0')
    {
      sendBuf[sendSize] = '\n';
      sendBuf[sendSize+1] = '\0';
      sendSize +=1;
      break;
    }
  }


  rc = WinsockStartup();
  if (rc == SOCKET_ERROR)
  {
    cout << "WSAStartup Error " << WSAGetLastError() << endl;
    return rc;
  }

  whoisSocket = socket(AF_INET, SOCK_STREAM,NULL);
  if (whoisSocket == INVALID_SOCKET)
  {
    cout << "Invalid Socket Error " << WSAGetLastError() << endl;
    return rc;
  }

  whoisAddr.sin_family = AF_INET;
  whoisAddr.sin_port = htons(WHOIS_PORT);
  whoisAddr.sin_addr.s_addr = inet_addr(WHOIS_SERVER_IP);
  if (whoisAddr.sin_addr.s_addr == INADDR_NONE)
  {
    cout << "Invalid IP Error !" << endl;
    return SOCKET_ERROR;
  }

  cout << "Connecting ...\n\n" << endl;
  rc = connect(whoisSocket, (SOCKADDR*) &whoisAddr, sizeof(whoisAddr));
  if (rc == SOCKET_ERROR)
  {
    cout << "Cannot connect to whois Server, Error: " << WSAGetLastError() << endl;
    return rc;
  }

  rc = send (whoisSocket, &sendBuf[0], sendSize , NULL);
  if(rc == SOCKET_ERROR)
  {
    cout << "Cannot send Data to whois Server, Error: " << WSAGetLastError() << endl;
    return rc;
  }



  rc = recv (whoisSocket, &recvBuf[0], sizeof(recvBuf), NULL);
  cout << "\n" << recvBuf << endl;


  rc = closesocket(whoisSocket);
  WSACleanup();


  return 0;
}


long WinsockStartup()
{
  long rc;

  WORD wVersionRequested;
  WSADATA wsaData;
  wVersionRequested = MAKEWORD( 2, 2 );

  rc = WSAStartup( wVersionRequested, &wsaData );
  return rc;
}
