summaryrefslogtreecommitdiff
path: root/tcpip.c
blob: 6a58fffe22910ee1f4ba4814651c563da4b9c9c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**********************************************************
 * tcpip.c
 *
 * Copyright 2004, Stefan Siegl <stesie@brokenpipe.de>, Germany
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Publice License,
 * version 2 or any later. The license is contained in the COPYING
 * file that comes with the cvsfs distribution.
 *
 * speak tcp/ip protocol, aka connect to tcp/ip sockets
 */

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif

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

#include "tcpip.h"

/* tcpip_connect
 *
 * try to connect to the specified tcp/ip socket, wrap to stdio.h's FILE*
 * structure and turn on line buffering
 */
FILE *
tcpip_connect(const char *hostname, int port)
{
  int sockfd;
  struct sockaddr_in addr;
  struct in_addr inaddr;
  struct hostent *host;
  FILE *handle;
  const char err_connect[] = PACKAGE ": unable to connect to cvs host";

  if(inet_aton(hostname, &inaddr))
    host = gethostbyaddr((char *) &inaddr, sizeof(inaddr), AF_INET);
  else
    host = gethostbyname(hostname);

  if(! host)
    {
      herror(err_connect);
      return NULL;
    }

  addr.sin_family = AF_INET;
  addr.sin_port = htons(port);
  memcpy(&addr.sin_addr, host->h_addr_list[0], sizeof(addr.sin_addr));

  if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
    {
      perror(err_connect);
      return NULL;
    }

  if(connect(sockfd, (struct sockaddr *) &addr, sizeof(addr)))
    {
      perror(err_connect);
      return NULL;
    }

  handle = fdopen(sockfd, "r+");
  if(! handle)
    {
      perror(err_connect);
      close(sockfd);
      return NULL;
    }

  if(setvbuf(handle, NULL, _IOLBF, 0))
    {
      perror(err_connect);
      fclose(handle);
      return NULL;
    }

  return handle;
}