The realization method of acquiring network traffic under Linux __linux

Source: Internet
Author: User
The data is read only through/proc/net/dev. Reproduced

#include
#include
#include

void SkipLine (FILE *f)
{
int ch;
do {
ch = getc (f);
while (ch!= ' n ' && ch!= EOF);
}

int main (int argc, char *argv[])
{
FILE *PND;
Char Buffer[bufsiz];
Char *interface;
struct Ifinfo {
Char Name[8];
unsigned int r_bytes, R_PKT, R_err, R_drop, R_fifo, R_frame;
unsigned int r_compr, r_mcast;
unsigned int x_bytes, X_PKT, X_err, X_drop, X_fifo, X_coll;
unsigned int x_carrier, X_COMPR;
IFC;
unsigned long long bin, bout, Lbin, lbout;
int-A;

if (argc!= 2) {
fprintf (stderr, "Usage:%s Interfacen", argv[0]);
Exit (1);
}

interface = Argv[1];

i = 1;
Lbin = 0; lbout = 0;

while (1) {
PND = fopen ("/proc/net/dev", "R");
if (!PND) {
fprintf (stderr, "%s:/proc/net/dev:%s", Argv[0], strerror (errno));
Exit (1);
}

/* SKIP Header * *
SkipLine (PND);
SkipLine (PND);

/* Get interface Info * *
do {
if (fscanf (PND, "%6[^:]:%u%u%u%u,%u%u%u%u%u%u%u?%u"%u%u%u),
&ifc.name,
&ifc.r_bytes, &ifc.r_pkt, &ifc.r_err, &ifc.r_drop,
&ifc.r_fifo, &ifc.r_frame, &IFC.R_COMPR, &ifc.r_mcast,
&ifc.x_bytes, &ifc.x_pkt, &ifc.x_err, &ifc.x_drop,
&ifc.x_fifo, &ifc.x_coll, &ifc.x_carrier, &IFC.X_COMPR)
!= 16) {
Exit (200);
}
SkipLine (PND);
while (strcmp (Ifc.name, interface));

Bin = ifc.r_bytes + (Lbin & ~0xffffffffull);
bout = Ifc.x_bytes + (lbout & ~0xffffffffull);

if (Bin < Lbin)
Bin + = (1ULL << 32);
if (Bout < lbout)
Bout + + (1ULL << 32);

if (!first) {
printf ("%d%Lu%lun", Time (NULL), (Bout-lbout) *8, (Bin-lbin) *8);
Fflush (stdout);
} else {
i = 0;
}

Lbin = bin; Lbout = bout;

Fclose (PND);

Sleep (1);
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.