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

network.c

#ifndef _NETWORK_C
#define _NETWORK_C

#include <stdio.h>
#include <stdint.h>
#include <string.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_udp: 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 , "init_sockaddr_in: unknown host: %s.\n" , hostname ) ;
      FAILURE ;
    }
    name->sin_addr = *(struct in_addr *) hostinfo->h_addr ;
  } else {
    name->sin_addr.s_addr = htonl ( INADDR_ANY ) ;
  }
}

void 
print_sockaddr_in ( FILE *fp , struct sockaddr_in a )
{
  fprintf ( fp , "sin_family      %d\n" , a.sin_family ) ;
  fprintf ( fp , "sin_port        %d\n" , a.sin_port ) ;
  fprintf ( fp , "sin_addr.s_addr %d\n" , a.sin_addr.s_addr);
}

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_inet: bind() failed" ) ;
    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 ;
}

#endif

Generated by  Doxygen 1.6.0   Back to index