2

I want to write application that takes Wireshark File and read all the packets inside this file. So i want to able to support several formats. Until now i can handle Libpcap, Pcapng and TcpDump. So i wonder hot to design my application. I was thinking to create abstract class:

 public abstract class WiresharkFile
    {
        private string _fileName;
        private int _packets;
        private string _duration;
        protected abstract IEnumerable<Packet> ReadPackets(string file);
    }

As you can see all the formats that inherit from this WiresharkFile have name, packet (each file contain several packets and duration). And also ReadPackets method because every format need to read the file in other way. So my question is in case i am choose file and want to read it's packets how can i know what the file format in order to run the correct ReadPackets method that i have for each format.

3
  • Is your problem to determine the type from the file? How do you distinguish them "manually"? By a suffix in the file name? By a special code at the beginning of the file?
    – Doc Brown
    Nov 5, 2015 at 11:46
  • prefix, x bytes at the beginning of the file.
    – mark yer
    Nov 5, 2015 at 12:08
  • I like the strategy pattern for this using interfaces instead of an abstract class for the file format reader. A factory pattern could still be used to keep the strategy choice outside of whatever component is processing the packets. Nov 5, 2015 at 15:08

1 Answer 1

3

What you are looking for is a Factory. In the most simple form, that is just a static method like

public abstract class WiresharkFile
{
     public static WiresharkFile WiresharkFileFactory(string filename)
     {
     //  ... logic here to create either a LibpcapWireSharkFile, a 
     //  ... PcapngWireSharkFile, or another subclass instance
     }
}  

If that method has a certain complexity, you may consider to move that method out of the WiresharkFile class to a separate factory class. And if you need those classes in an extensible library, where you can add new derivations afterwards without changing the factory code, you may have a look into the abstract factory pattern.

Note that when your factory creates the object, you can already pass the filename to that object, so your ReadPackets() methods should not need any filename parameter any more.

2
  • So inside this i am just do WiresharkFile = new LibpcapWireSharkFile()...
    – mark yer
    Nov 5, 2015 at 12:21
  • @markyer: yes, but you obviously have to add some logic to determine which subclass is the correct one.
    – Doc Brown
    Nov 5, 2015 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.