Reputation: 490
In libpcap
I have this code for sniffing and printing packets length
int main(int argc, char *argv[])
{
pcap_t *handle; /* Session handle */
char *dev; /* The device to sniff on */
char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */
struct bpf_program fp; /* The compiled filter */
char filter_exp[] = "port 23"; /* The filter expression */
bpf_u_int32 mask; /* Our netmask */
bpf_u_int32 net; /* Our IP */
struct pcap_pkthdr header; /* The header that pcap gives us */
const u_char *packet; /* The actual packet */
/* Define the device */
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
fprintf(stderr, "Couldn't find default device: %s\n", errbuf);
return(2);
}
/* Find the properties for the device */
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Couldn't get netmask for device %s: %s\n", dev, errbuf);
net = 0;
mask = 0;
}
/* Open the session in promiscuous mode */
handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
return(2);
}
/* Compile and apply the filter */
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
return(2);
}
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
return(2);
}
while(1)
{
packet = pcap_next(handle, &header);
printf("packet len = [%d]\n", header.len);
}
pcap_close(handle);
return(0);
}
I want to set pointer to header.len
before loop and print it each iteration:
bpf_u_int32 * len= &header.len
while(1)
{
packet = pcap_next(handle, &header);
printf("packet len = [%d]\n", *len);
}
Does that work or can the address of header.len
change in each iteration?
Upvotes: 0
Views: 164
Reputation: 176
The address of header
won't change within that loop.
However, there's no reason to do
bpf_u_int32 * len= &header.len
while(1)
{
packet = pcap_next(handle, &header);
printf("packet len = [%d]\n", *len);
}
rather than just
while(1)
{
packet = pcap_next(handle, &header);
printf("packet len = [%d]\n", header.len);
}
You'll get the same answer and, in fact, a compiler may even generate the same code for that. (This isn't your grandfather's C; C compilers do a lot more optimizing and other code transformation than they did in the old days.)
Putting a pointer to header.len
into a variable, and dereferencing the pointer, isn't inherently more efficient. The compiler might well generate code to do that if, for example, "load/push what a register points to" is more efficient than "load/push from an offset from what a register points to".
Upvotes: 1