/* Copyright (c) 2007 DN-Systems GmbH http://rfdump.org

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */

/* $Header: /cvs/rfdump/src/tcpconnect.c,v 1.3 2007/11/16 06:21:06 dirk Exp $ */

#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int tcp_connect(const char *hostname, const char *portstr)
{
  struct sockaddr_in addr; memset(&addr, 0, sizeof(addr));
  struct in_addr saddr; memset(&saddr, 0, sizeof(saddr));

  // determine port
  int port=strtol(portstr,0,0);
  if(port<=0 || port >= 65536)
    {
      // try to interpret as service name
      struct servent *se=getservbyname(portstr, "tcp");
      if(!se)
	return -1;
      addr.sin_port=se->s_port;
    }
  else
    addr.sin_port = htons(port);

  int protonum=0;
  struct protoent *p=getprotobyname("IP");
  if(p)
    protonum=p->p_proto;


  /* try dotted decimal */
  saddr.s_addr = inet_addr(hostname);
  if(saddr.s_addr != -1)
    {
      addr.sin_family = AF_INET;
      addr.sin_addr = saddr;
    }
  else
    {
      /* try dns name */
      struct hostent *host = gethostbyname(hostname);
      if (host==0)
	return -1;
      addr.sin_family = host->h_addrtype;
      addr.sin_addr.s_addr = *((unsigned long *)host->h_addr_list[0]);
    }

  int sock = socket(addr.sin_family, SOCK_STREAM, protonum);
  if (sock < 0)
    {
      perror("could not create socket");
      return -1;
    }

  if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
    {
      perror("could not connect");
      close(sock);
      return -1;
    }

  return sock;
}
