Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- input file : pcap file
- Usage : ./a.out [filename]
- Output is stdout with csv format
- export tcp, udp, icmp
- csv format : ts,Transport Layer protocol,srcIP,srcPort,dstIP,dstPort,payload_size
- Issue : ipv4 packets with but not udp, tcp, icmp packet will have some excess line
- */
- #include <iostream>
- #include <pcap.h>
- #include <net/ethernet.h>
- #include <netinet/ip.h>
- #include <netinet/in.h>
- #include <netinet/tcp.h>
- #include <netinet/udp.h>
- #include <netinet/ip_icmp.h>
- #include <arpa/inet.h>
- using namespace std;
- void call_back(u_char *user, const pcap_pkthdr *h, const u_char *bytes);
- int main(int argc, char **argv) {
- char *dev;
- char errbuf[PCAP_ERRBUF_SIZE];
- if (argc != 2) {
- cerr << "Usage : " << argv[0] << " filename" << endl;
- return 1;
- }
- pcap_t *descr;
- descr = pcap_open_offline(argv[1], errbuf);
- if (descr == NULL) {
- cerr << "pcap_open_file failed" << endl;
- return 2;
- }
- if (pcap_loop(descr, 0, call_back, NULL) < 0) {
- cerr << "pcap_loop() failed: " << pcap_geterr(descr);
- return 3;
- }
- return 0;
- }
- void call_back(u_char *user, const pcap_pkthdr *h, const u_char *bytes) {
- const ether_header *ethernetHeader;
- const ip *ipHeader;
- const tcphdr *tcpHeader;
- const udphdr *udpHeader;
- char sourceIP[INET_ADDRSTRLEN];
- char dstIP[INET_ADDRSTRLEN];
- u_int sourcePort, dstPort;
- int dataLength = 0;
- ethernetHeader = (ether_header *)bytes;
- if (ntohs(ethernetHeader->ether_type) == ETHERTYPE_IP) {
- printf("%ld.%6ld,", h->ts); //print time
- ipHeader = (ip *)(bytes + sizeof(ether_header));
- inet_ntop(AF_INET, &(ipHeader->ip_src), sourceIP, INET_ADDRSTRLEN);
- inet_ntop(AF_INET, &(ipHeader->ip_dst), dstIP, INET_ADDRSTRLEN);
- if (ipHeader->ip_p == IPPROTO_TCP) {
- tcpHeader = (tcphdr *)(bytes + sizeof(ether_header) + sizeof(ip));
- sourcePort = ntohs(tcpHeader->source);
- dstPort = ntohs(tcpHeader->dest);
- dataLength = h->len - (sizeof(ether_header) + sizeof(ip) + sizeof(tcphdr));
- cout << "tcp,";
- } else if (ipHeader->ip_p == IPPROTO_UDP) {
- udpHeader = (udphdr *)(bytes + sizeof(ether_header) + sizeof(ip));
- sourcePort = ntohs(udpHeader->uh_sport);
- dstPort = ntohs(udpHeader->uh_dport);
- dataLength = h->len - (sizeof(ether_header) + sizeof(ip) + sizeof(udphdr));
- cout << "udp,";
- } else if (ipHeader->ip_p == IPPROTO_ICMP) {
- sourcePort = 0;
- dstPort = 0;
- dataLength = h->len - (sizeof(ether_header) + sizeof(ip) + sizeof(icmphdr));
- cout << "icmp,";
- }
- cout << sourceIP << ',' << sourcePort << ',' << dstIP << ',' << dstPort << ',' << dataLength<< endl;
- }
- }
Add Comment
Please, Sign In to add comment