how to send a tcp packet using libpcap?
Hi Everybody,
Iam new to linux and libpcap.In the prog below I try to send a TCP SYN packet. But it gives segmentation fault on execution.can anyone explain wats happening??
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <netinet/if_ether.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pcap.h>
#define srcip "10.142.17.127"
#define dstip "10.142.17.127"
#define sport 1111
#define dport 23
main()
{
pcap_t *descr;
char error[PCAP_ERRBUF_SIZE];
int i;
char *dev;
struct iphdr *iphdr;
struct tcphdr *tcp;
// u_char packet[sizeof(struct iphdr)+sizeof(struct tcphdr)+sizeof(struct ethhdr)];
char *packet,*packet1,*chpacket;
int data_size = 20;
int packet_size;
int tcp_opt_size = 0;
dev=pcap_lookupdev(error);
/*Open the device */
if((descr = pcap_open_live(dev, 100, 1, 1000, error) ) == NULL)
{
fprintf(stderr,"\nError opening device: %s\n", error);
return;
}
tcp = (struct tcphdr *) packet1;
tcp->source=htons(sport);
tcp->dest = htons(dport);
tcp->seq = 12345; //htonl(rand());
tcp->ack_seq = 0;
tcp->doff = 5;
tcp->res1=0;
tcp->window = 512;
tcp->syn = 1;
tcp->check=0;
iphdr=(struct iphdr *)packet;
iphdr->ihl = 20;
iphdr->version = 4;
iphdr->tot_len = htons(sizeof (struct iphdr));
iphdr->id = 1234;
iphdr->ttl = 250;
iphdr->frag_off= htons((unsigned short) 0x2000);
iphdr->protocol = 6;
iphdr->saddr =inet_addr(srcip);
iphdr->daddr =inet_addr(dstip);
iphdr->check = 0;
chpacket=(char *)packet;
bcopy(packet1,chpacket+sizeof(struct iphdr), sizeof(packet1));
printf("%s",chpacket);
if(pcap_sendpacket(descr,chpacket,packet_size)==-1)
perror("pcap_sendpacket");
else
printf("packet sent");
}
Last edited by kalps; 03-05-2009 at 01:31 AM.
|