Logo Search packages:      
Sourcecode: jack-tools version File versions  Download package

network.c

#ifndef _NETWORK_C
#define _NETWORK_C

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

int
socket_udp ( int flags )
{
  int fd = socket ( AF_INET , SOCK_DGRAM , flags ) ;
  if ( fd < 0 ) {
    perror ( "socket() failed" ) ;
    FAILURE ;
  }
  return fd ;
}

void
init_sockaddr_in ( struct sockaddr_in *name , const char *hostname , uint16_t port )
{
  name->sin_family = AF_INET ;
  name->sin_port = htons ( port ) ;
  if ( hostname ) {
    struct hostent *hostinfo = gethostbyname ( hostname ) ;
    if (hostinfo == NULL) {
      fprintf ( stderr , "gethostbyname() faile: %s.\n" , hostname ) ;
      FAILURE ;
    }
    name->sin_addr = *(struct in_addr *) hostinfo->h_addr ;
  } else {
    name->sin_addr.s_addr = htonl ( INADDR_ANY ) ;
  }
}

void
bind_inet ( int fd , const char *hostname , int port )
{
  struct sockaddr_in name ;
  init_sockaddr_in ( &name , hostname , port ) ;
  int err = bind ( fd , (struct sockaddr *)&name , sizeof(name) ) ;
  if ( err < 0 ) {
    perror ( "bind() failed" ) ;
    FAILURE ;
  }
}

int
xsendto ( int fd , const void *data , size_t n , int flags , struct sockaddr *addr , socklen_t length ) 
{
  int err = sendto ( fd , data , n , flags , addr , length ) ;
  if ( err < 0 ) {
    perror ( "sendto() failed" ) ;
    FAILURE ;
  }
  return err ;
}

void
sendto_exactly ( int fd , const char *data , int n , struct sockaddr_in address )
{
  int err = xsendto ( fd , data , n , 0 , (struct sockaddr *)&address , sizeof(address) ) ;
  if ( err != n ) {
    fprintf ( stderr , "sendto_exactly: partial write\n" ) ;
    FAILURE ;
  }
}

int
xrecv ( int fd , void *buf , size_t n , int flags )
{
  int err = recv ( fd , buf , n , flags ) ;
  if ( err < 0 ) {
    perror ( "recv() failed" ) ;
    FAILURE ;
  }
  return err ;
}

void
recv_exactly ( int fd , void *buf , size_t n , int flags )
{
  int err = (int) xrecv ( fd , buf , n , flags ) ;
  if ( err != n ) {
    fprintf ( stderr , "recv_exactly: partial recv (%d != %d)\n" , err , n );
    FAILURE ;
  }
}

#endif

Generated by  Doxygen 1.6.0   Back to index