ITL Lab Manual

send.c


/*
  send.c
  written by Richard Gordon
  last modified 2/27/03

  This program sends n packets on a specific interface each containing
  a specified sequence of nibbles indicated by their hex values.
  It is called by

  send <n> <interface> <string of hex digits>

  where <n> is the number of packets to send,
  <interface> is "eth0", "eth1", etc.,
  and <string of hex digits> is a sequence of hex characters indicating
  the packet contents to send. Each character is packed into one nibble
  of the packet. If there are an odd number of characters a 0x0 is
  appended.
*/

#define BUFFER_LEN 1600

#include <stdio.h>
#include <ctype.h>
//#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <linux/if_ether.h>
#include <unistd.h>

int
hex_char_to_binary( char c );

int
main( int argc, char* argv[] )
{
  struct sockaddr address;
  char buffer[BUFFER_LEN];
  int sock;
  int packet_count;
  int octet_count;
  int i;
  char* interface;

  /* the call must be of the form send <n> <interface> <string of hex digits>*/
  if (argc != 4)
  {
    fprintf( stderr, "usage: send <n> <interface> <string of hex digits>\n" );
    exit(1);
  }
  packet_count = atoi( argv[1] );
  interface = argv[2];
  octet_count = (strlen( argv[ 3 ] )+1) / 2 ;
  
  /* pack the hex digits into the buffer two per octet */
  for (i=0; i<octet_count; ++i)
    buffer[ i ] = hex_char_to_binary( argv[ 3 ][ 2*i ] ) << 4 | hex_char_to_binary( argv[ 3 ][ 2*i+1 ] );

  /* build address data structure */
  memset( &address, 0, sizeof( address ) );
  address.sa_family = AF_INET;
  strncpy( address.sa_data, interface, sizeof(address.sa_data) );

  if ((sock = socket( PF_INET, SOCK_PACKET, htons(ETH_P_ALL) ))<0)
  {
    perror( "send: socket" );
    exit(1);
  }

  /* main loop */
  for (i=0; i<packet_count; i++ )
  {
    sendto( sock, buffer, octet_count, 0, &address, sizeof( address ) );
  }
  close( sock );

}

/* convert hex digit to corresponding binary value */
int
hex_char_to_binary( char c )
{
  int result;
	
  if (isxdigit( c ))
  {
	if (isdigit( c ) )
      result = c - '0';
    else
      result = toupper( c ) - 'A' + 10;
  }
  else if (c != 0)	// in case the hex_digit string has an odd length
  {
    fprintf( stderr, "non hex digiti found in string\n" );
    exit(1);
  }
	
	return result;
}


all: send

send: send.c
	gcc -o send send.c

clean:
	-rm -f *~ send

| Sonoma State University | CS Department | Computer and Engineering Science | Internet Teaching Laboratory | Lab Manual Table of Contents |