Logo Search packages:      
Sourcecode: cabber version File versions  Download package

socket.c

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


int sock;


u_long
resolve_host (u_char * host)
{
  long i;
  struct hostent *he;

  if ((i = inet_addr (host)) == -1)
    {
      if (!(he = gethostbyname (host)))
      return 0;
      else
      return (*(u_long *) he->h_addr);
    }
  return (i);
}

int
make_socket (u_char * server, uint16_t port)
{
  int sock;
  struct sockaddr_in name;

  name.sin_family = AF_INET;
  name.sin_port = htons (port);

  if (!(name.sin_addr.s_addr = resolve_host (server)))
    return -1;

  if ((sock = socket (PF_INET, SOCK_STREAM, 0)) < 0)
    {
      perror ("socket (socket.c:33)");
      exit (EXIT_FAILURE);
    }

  if (connect (sock, (struct sockaddr *) &name, sizeof (name)) < 0)
    {
      perror ("connect (socket.c:39)");
      exit (EXIT_FAILURE);
    }

  return sock;
}

int
connectJabber (char *server, int jabberport)
{
  sock = make_socket (server, jabberport);
  return sock;
}


int
senddata (char *buffer)
{
  if ((send (sock, buffer, strlen (buffer), 0)) == -1)
    return 0;
  else
    return 1;
}

char *
receivedata (void)
{
  int i = 1;
  int end = 0;
  int tambuffer = 128;
  char *buffer = malloc (tambuffer);
  char *retval = malloc (tambuffer + 1);
  char *aux;

  memset (retval, 0, tambuffer);
  memset (buffer, 0, tambuffer + 1);

  while (!end)
    {
      recv (sock, buffer, tambuffer, 0);

      if (i == 1)
      strcpy (retval, buffer);
      else
      {
        retval = realloc (retval, (tambuffer * i) + 1);
        strncat (retval, buffer, tambuffer + 1);
      }
      i++;
      aux = retval + strlen (retval) - 1;
      if (*aux != '>')
      end = 0;
      else
      end = 1;
      memset (buffer, 0, tambuffer);
    }
#ifdef DEBUG
  {
    FILE *fp = fopen ("/tmp/socket.log", "a+");
    fprintf (fp, "--> %s\n", retval);
    fclose (fp);
  }
#endif
  return retval;
}

int
check_io (int fd1, int fd2)
{
  int n = 0, i;
  fd_set fds;
  int io_pending = 0;

  i = fd1;
  if (fd2 > fd1)
    i = fd2;

  FD_ZERO (&fds);
  if (fd1 >= 0)
    FD_SET (fd1, &fds);
  else
    fd1 = 0;
  if (fd2 >= 0)
    FD_SET (fd2, &fds);
  else
    fd2 = 0;

  if (fd2 == 0 && io_pending)
    n = 2;
  else if (select (i + 1, &fds, NULL, NULL, NULL) > 0)
    n = 1 * (FD_ISSET (fd1, &fds) > 0) + 2 * (FD_ISSET (fd2, &fds) > 0);

  return (n);
}

Generated by  Doxygen 1.6.0   Back to index