Monday, July 19, 2010

udp send

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

int fd,num_pkt;
void sig_handler(int num)
{
printf("sent %d packets\n",num_pkt);
close(fd);
exit(1);
}

void print_pkt(unsigned *buf, int len)
{
int j;

for(j=0; j< len; j++)
{
if(j%16 == 0 || j != 0)
printf("\n");
printf("%02x ",buf[j]);
}
printf("\n");
}

struct _udp_packet
{
struct udphdr udp;
unsigned char data[22];
}__attribute__((__packed__));

int main(int argc, char **argv)
{
struct sockaddr_in sin;
struct _udp_packet udpkt;

if(argc != 4)
{
printf("Usage:\n./udp \n");
exit(1);
}

fd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
if(fd < 0)
{
perror("socket");
exit(1);
}

sin.sin_family = AF_INET;
//sin.sin_port = htons(atoi(argv[1]);
sin.sin_addr.s_addr = inet_addr(argv[3]);

udpkt.udp.source = htons(atoi(argv[2]));
udpkt.udp.dest = htons(atoi(argv[1]));
udpkt.udp.len = htons(8 + sizeof(udpkt.data));
udpkt.udp.check = 0x0000;

memset(udpkt.data, 0, sizeof(udpkt.data));

signal(SIGINT,sig_handler);
signal(SIGQUIT,sig_handler);
while(1)
{

if(sendto(fd, (unsigned char*)&udpkt, 30, 0, (struct sockaddr *)&sin, sizeof(struct sockaddr)) < 0)
{
perror("sendto");
close(fd);
exit(1);
}

num_pkt++;
sleep(1);
}

return 0;
}