Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I am interested in storing packets I sniff using PCAP.

As I preallocate the memory I need - i.e. a multiple of the MTU of the interface I am sniffing from, I would like to discover how much memory I need before opening the live session.

Is it possible to query PCAP for getting the MTU of the sniffed interface ?

How can I get this information otherwise (possibly using system libraries) ?

Thanks

share|improve this question

2 Answers 2

One option on linux would be the sysfs file mtu in /sys/class/net/devicename

$ cat /sys/class/net/eth0/mtu /sys/class/net/lo/mtu
1500
16436
share|improve this answer
up vote 2 down vote accepted

There is not a straightforward way to do so in PCAP (no API).

However, for Linux >=2.6 Solvent posted a simple solution that is reading a file like the following: /sys/class/net/INTERFACE_X/mtu. It is trivial to do it in C.

int getMTU(char *name) {
FILE *f;
char buf[128];
char *line = NULL;
ssize_t count;
size_t len = 0;
int mtu;

snprintf(buf, sizeof(buf), "/sys/class/net/%s/mtu", name);
f = fopen(buf, "r");
if(!f) {
    perror("Error opening:");
    exit(EXIT_FAILURE);
}
count = getline(&line, &len, f);

if (count == -1) {
    perror("Error opening:");
    exit(EXIT_FAILURE);
}
sscanf(line, "%d\n", &mtu);
fclose(f);

return mtu;
}

Reading the PCAP source, I found out that the PCAP developers used a more complex, yet elegant solution to read the interface MTU invoking ioctl. This is a simplified version I wrote:

#include <sys/ioctl.h>
#include <net/if.h>

int get_mtu(int fd, const char *device) {
struct ifreq ifr;

if (!device)
    return 65535;

memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));

if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
    perror("Error opening:");
    exit(EXIT_FAILURE);
}

return ifr.ifr_mtu;
}

For further references, man netdevice is suggested.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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