[go: up one dir, main page]

Struct NetworkData

Source
pub struct NetworkData { /* private fields */ }
Expand description

Getting volume of received and transmitted data.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("[{interface_name}] {network:?}");
}

Implementations§

Source§

impl NetworkData

Source

pub fn received(&self) -> u64

Returns the number of received bytes since the last refresh.

If you want the total number of bytes received, take a look at the total_received method.

use sysinfo::Networks;
use std::{thread, time};

let mut networks = Networks::new_with_refreshed_list();
// Waiting a bit to get data from network...
thread::sleep(time::Duration::from_millis(10));
// Refreshing again to generate diff.
networks.refresh(true);

for (interface_name, network) in &networks {
    println!("in: {} B", network.received());
}
Examples found in repository?
examples/simple.rs (line 314)
149fn interpret_input(
150    input: &str,
151    sys: &mut System,
152    networks: &mut Networks,
153    disks: &mut Disks,
154    components: &mut Components,
155    users: &mut Users,
156) -> bool {
157    match input.trim() {
158        "help" => print_help(),
159        "refresh_disks" => {
160            writeln!(&mut io::stdout(), "Refreshing disk list...");
161            disks.refresh(true);
162            writeln!(&mut io::stdout(), "Done.");
163        }
164        "refresh_users" => {
165            writeln!(&mut io::stdout(), "Refreshing user list...");
166            users.refresh();
167            writeln!(&mut io::stdout(), "Done.");
168        }
169        "refresh_networks" => {
170            writeln!(&mut io::stdout(), "Refreshing network list...");
171            networks.refresh(true);
172            writeln!(&mut io::stdout(), "Done.");
173        }
174        "refresh_components" => {
175            writeln!(&mut io::stdout(), "Refreshing component list...");
176            components.refresh(true);
177            writeln!(&mut io::stdout(), "Done.");
178        }
179        "refresh_cpu" => {
180            writeln!(&mut io::stdout(), "Refreshing CPUs...");
181            sys.refresh_cpu_all();
182            writeln!(&mut io::stdout(), "Done.");
183        }
184        "signals" => {
185            let mut nb = 1i32;
186
187            for sig in signals {
188                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189                nb += 1;
190            }
191        }
192        "cpus" => {
193            // Note: you should refresh a few times before using this, so that usage statistics
194            // can be ascertained
195            writeln!(
196                &mut io::stdout(),
197                "number of physical cores: {}",
198                sys.physical_core_count()
199                    .map(|c| c.to_string())
200                    .unwrap_or_else(|| "Unknown".to_owned()),
201            );
202            writeln!(
203                &mut io::stdout(),
204                "total CPU usage: {}%",
205                sys.global_cpu_usage(),
206            );
207            for cpu in sys.cpus() {
208                writeln!(&mut io::stdout(), "{cpu:?}");
209            }
210        }
211        "memory" => {
212            writeln!(
213                &mut io::stdout(),
214                "total memory:     {: >10} KB",
215                sys.total_memory() / 1_000
216            );
217            writeln!(
218                &mut io::stdout(),
219                "available memory: {: >10} KB",
220                sys.available_memory() / 1_000
221            );
222            writeln!(
223                &mut io::stdout(),
224                "used memory:      {: >10} KB",
225                sys.used_memory() / 1_000
226            );
227            writeln!(
228                &mut io::stdout(),
229                "total swap:       {: >10} KB",
230                sys.total_swap() / 1_000
231            );
232            writeln!(
233                &mut io::stdout(),
234                "used swap:        {: >10} KB",
235                sys.used_swap() / 1_000
236            );
237        }
238        "quit" | "exit" => return true,
239        "all" => {
240            for (pid, proc_) in sys.processes() {
241                writeln!(
242                    &mut io::stdout(),
243                    "{}:{} status={:?}",
244                    pid,
245                    proc_.name().to_string_lossy(),
246                    proc_.status()
247                );
248            }
249        }
250        "frequency" => {
251            for cpu in sys.cpus() {
252                writeln!(
253                    &mut io::stdout(),
254                    "[{}] {} MHz",
255                    cpu.name(),
256                    cpu.frequency(),
257                );
258            }
259        }
260        "vendor_id" => {
261            writeln!(
262                &mut io::stdout(),
263                "vendor ID: {}",
264                sys.cpus()[0].vendor_id()
265            );
266        }
267        "brand" => {
268            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269        }
270        "load_avg" => {
271            let load_avg = System::load_average();
272            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
273            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
274            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275        }
276        e if e.starts_with("show ") => {
277            let tmp: Vec<&str> = e.split(' ').collect();
278
279            if tmp.len() != 2 {
280                writeln!(
281                    &mut io::stdout(),
282                    "show command takes a pid or a name in parameter!"
283                );
284                writeln!(&mut io::stdout(), "example: show 1254");
285            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286                match sys.process(pid) {
287                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289                };
290            } else {
291                let proc_name = tmp[1];
292                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293                    writeln!(
294                        &mut io::stdout(),
295                        "==== {} ====",
296                        proc_.name().to_string_lossy()
297                    );
298                    writeln!(&mut io::stdout(), "{proc_:?}");
299                }
300            }
301        }
302        "temperature" => {
303            for component in components.iter() {
304                writeln!(&mut io::stdout(), "{component:?}");
305            }
306        }
307        "network" => {
308            for (interface_name, data) in networks.iter() {
309                writeln!(
310                    &mut io::stdout(),
311                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
312                    interface_name,
313                    data.mac_address(),
314                    data.received(),
315                    data.total_received(),
316                    data.transmitted(),
317                    data.total_transmitted(),
318                );
319            }
320        }
321        "show" => {
322            writeln!(
323                &mut io::stdout(),
324                "'show' command expects a pid number or a process name"
325            );
326        }
327        e if e.starts_with("kill ") => {
328            let tmp: Vec<&str> = e.split(' ').collect();
329
330            if tmp.len() != 3 {
331                writeln!(
332                    &mut io::stdout(),
333                    "kill command takes the pid and a signal number in parameter!"
334                );
335                writeln!(&mut io::stdout(), "example: kill 1254 9");
336            } else {
337                let pid = Pid::from_str(tmp[1]).unwrap();
338                let signal = i32::from_str(tmp[2]).unwrap();
339
340                if signal < 1 || signal > 31 {
341                    writeln!(
342                        &mut io::stdout(),
343                        "Signal must be between 0 and 32 ! See the signals list with the \
344                         signals command"
345                    );
346                } else {
347                    match sys.process(pid) {
348                        Some(p) => {
349                            if let Some(res) =
350                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
351                            {
352                                writeln!(&mut io::stdout(), "kill: {res}");
353                            } else {
354                                writeln!(
355                                    &mut io::stdout(),
356                                    "kill: signal not supported on this platform"
357                                );
358                            }
359                        }
360                        None => {
361                            writeln!(&mut io::stdout(), "pid not found");
362                        }
363                    };
364                }
365            }
366        }
367        "disks" => {
368            for disk in disks {
369                writeln!(&mut io::stdout(), "{disk:?}");
370            }
371        }
372        "users" => {
373            for user in users {
374                writeln!(
375                    &mut io::stdout(),
376                    "{:?} => {:?}",
377                    user.name(),
378                    user.groups()
379                );
380            }
381        }
382        "boot_time" => {
383            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384        }
385        "uptime" => {
386            let up = System::uptime();
387            let mut uptime = up;
388            let days = uptime / 86400;
389            uptime -= days * 86400;
390            let hours = uptime / 3600;
391            uptime -= hours * 3600;
392            let minutes = uptime / 60;
393            writeln!(
394                &mut io::stdout(),
395                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396            );
397        }
398        x if x.starts_with("refresh") => {
399            if x == "refresh" {
400                writeln!(&mut io::stdout(), "Getting processes' information...");
401                sys.refresh_all();
402                writeln!(&mut io::stdout(), "Done.");
403            } else if x.starts_with("refresh ") {
404                writeln!(&mut io::stdout(), "Getting process' information...");
405                if let Some(pid) = x
406                    .split(' ')
407                    .filter_map(|pid| pid.parse().ok())
408                    .take(1)
409                    .next()
410                {
411                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413                    } else {
414                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415                    }
416                } else {
417                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
418                }
419            } else {
420                writeln!(
421                    &mut io::stdout(),
422                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423                     list.",
424                );
425            }
426        }
427        "pid" => {
428            writeln!(
429                &mut io::stdout(),
430                "PID: {}",
431                sysinfo::get_current_pid().expect("failed to get PID")
432            );
433        }
434        "system" => {
435            writeln!(
436                &mut io::stdout(),
437                "System name:              {}\n\
438                 System kernel version:    {}\n\
439                 System OS version:        {}\n\
440                 System OS (long) version: {}\n\
441                 System host name:         {}",
442                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447            );
448        }
449        e => {
450            writeln!(
451                &mut io::stdout(),
452                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453                 list.",
454            );
455        }
456    }
457    false
458}
Source

pub fn total_received(&self) -> u64

Returns the total number of received bytes.

If you want the amount of received bytes since the last refresh, take a look at the received method.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("in: {} B", network.total_received());
}
Examples found in repository?
examples/simple.rs (line 315)
149fn interpret_input(
150    input: &str,
151    sys: &mut System,
152    networks: &mut Networks,
153    disks: &mut Disks,
154    components: &mut Components,
155    users: &mut Users,
156) -> bool {
157    match input.trim() {
158        "help" => print_help(),
159        "refresh_disks" => {
160            writeln!(&mut io::stdout(), "Refreshing disk list...");
161            disks.refresh(true);
162            writeln!(&mut io::stdout(), "Done.");
163        }
164        "refresh_users" => {
165            writeln!(&mut io::stdout(), "Refreshing user list...");
166            users.refresh();
167            writeln!(&mut io::stdout(), "Done.");
168        }
169        "refresh_networks" => {
170            writeln!(&mut io::stdout(), "Refreshing network list...");
171            networks.refresh(true);
172            writeln!(&mut io::stdout(), "Done.");
173        }
174        "refresh_components" => {
175            writeln!(&mut io::stdout(), "Refreshing component list...");
176            components.refresh(true);
177            writeln!(&mut io::stdout(), "Done.");
178        }
179        "refresh_cpu" => {
180            writeln!(&mut io::stdout(), "Refreshing CPUs...");
181            sys.refresh_cpu_all();
182            writeln!(&mut io::stdout(), "Done.");
183        }
184        "signals" => {
185            let mut nb = 1i32;
186
187            for sig in signals {
188                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189                nb += 1;
190            }
191        }
192        "cpus" => {
193            // Note: you should refresh a few times before using this, so that usage statistics
194            // can be ascertained
195            writeln!(
196                &mut io::stdout(),
197                "number of physical cores: {}",
198                sys.physical_core_count()
199                    .map(|c| c.to_string())
200                    .unwrap_or_else(|| "Unknown".to_owned()),
201            );
202            writeln!(
203                &mut io::stdout(),
204                "total CPU usage: {}%",
205                sys.global_cpu_usage(),
206            );
207            for cpu in sys.cpus() {
208                writeln!(&mut io::stdout(), "{cpu:?}");
209            }
210        }
211        "memory" => {
212            writeln!(
213                &mut io::stdout(),
214                "total memory:     {: >10} KB",
215                sys.total_memory() / 1_000
216            );
217            writeln!(
218                &mut io::stdout(),
219                "available memory: {: >10} KB",
220                sys.available_memory() / 1_000
221            );
222            writeln!(
223                &mut io::stdout(),
224                "used memory:      {: >10} KB",
225                sys.used_memory() / 1_000
226            );
227            writeln!(
228                &mut io::stdout(),
229                "total swap:       {: >10} KB",
230                sys.total_swap() / 1_000
231            );
232            writeln!(
233                &mut io::stdout(),
234                "used swap:        {: >10} KB",
235                sys.used_swap() / 1_000
236            );
237        }
238        "quit" | "exit" => return true,
239        "all" => {
240            for (pid, proc_) in sys.processes() {
241                writeln!(
242                    &mut io::stdout(),
243                    "{}:{} status={:?}",
244                    pid,
245                    proc_.name().to_string_lossy(),
246                    proc_.status()
247                );
248            }
249        }
250        "frequency" => {
251            for cpu in sys.cpus() {
252                writeln!(
253                    &mut io::stdout(),
254                    "[{}] {} MHz",
255                    cpu.name(),
256                    cpu.frequency(),
257                );
258            }
259        }
260        "vendor_id" => {
261            writeln!(
262                &mut io::stdout(),
263                "vendor ID: {}",
264                sys.cpus()[0].vendor_id()
265            );
266        }
267        "brand" => {
268            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269        }
270        "load_avg" => {
271            let load_avg = System::load_average();
272            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
273            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
274            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275        }
276        e if e.starts_with("show ") => {
277            let tmp: Vec<&str> = e.split(' ').collect();
278
279            if tmp.len() != 2 {
280                writeln!(
281                    &mut io::stdout(),
282                    "show command takes a pid or a name in parameter!"
283                );
284                writeln!(&mut io::stdout(), "example: show 1254");
285            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286                match sys.process(pid) {
287                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289                };
290            } else {
291                let proc_name = tmp[1];
292                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293                    writeln!(
294                        &mut io::stdout(),
295                        "==== {} ====",
296                        proc_.name().to_string_lossy()
297                    );
298                    writeln!(&mut io::stdout(), "{proc_:?}");
299                }
300            }
301        }
302        "temperature" => {
303            for component in components.iter() {
304                writeln!(&mut io::stdout(), "{component:?}");
305            }
306        }
307        "network" => {
308            for (interface_name, data) in networks.iter() {
309                writeln!(
310                    &mut io::stdout(),
311                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
312                    interface_name,
313                    data.mac_address(),
314                    data.received(),
315                    data.total_received(),
316                    data.transmitted(),
317                    data.total_transmitted(),
318                );
319            }
320        }
321        "show" => {
322            writeln!(
323                &mut io::stdout(),
324                "'show' command expects a pid number or a process name"
325            );
326        }
327        e if e.starts_with("kill ") => {
328            let tmp: Vec<&str> = e.split(' ').collect();
329
330            if tmp.len() != 3 {
331                writeln!(
332                    &mut io::stdout(),
333                    "kill command takes the pid and a signal number in parameter!"
334                );
335                writeln!(&mut io::stdout(), "example: kill 1254 9");
336            } else {
337                let pid = Pid::from_str(tmp[1]).unwrap();
338                let signal = i32::from_str(tmp[2]).unwrap();
339
340                if signal < 1 || signal > 31 {
341                    writeln!(
342                        &mut io::stdout(),
343                        "Signal must be between 0 and 32 ! See the signals list with the \
344                         signals command"
345                    );
346                } else {
347                    match sys.process(pid) {
348                        Some(p) => {
349                            if let Some(res) =
350                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
351                            {
352                                writeln!(&mut io::stdout(), "kill: {res}");
353                            } else {
354                                writeln!(
355                                    &mut io::stdout(),
356                                    "kill: signal not supported on this platform"
357                                );
358                            }
359                        }
360                        None => {
361                            writeln!(&mut io::stdout(), "pid not found");
362                        }
363                    };
364                }
365            }
366        }
367        "disks" => {
368            for disk in disks {
369                writeln!(&mut io::stdout(), "{disk:?}");
370            }
371        }
372        "users" => {
373            for user in users {
374                writeln!(
375                    &mut io::stdout(),
376                    "{:?} => {:?}",
377                    user.name(),
378                    user.groups()
379                );
380            }
381        }
382        "boot_time" => {
383            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384        }
385        "uptime" => {
386            let up = System::uptime();
387            let mut uptime = up;
388            let days = uptime / 86400;
389            uptime -= days * 86400;
390            let hours = uptime / 3600;
391            uptime -= hours * 3600;
392            let minutes = uptime / 60;
393            writeln!(
394                &mut io::stdout(),
395                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396            );
397        }
398        x if x.starts_with("refresh") => {
399            if x == "refresh" {
400                writeln!(&mut io::stdout(), "Getting processes' information...");
401                sys.refresh_all();
402                writeln!(&mut io::stdout(), "Done.");
403            } else if x.starts_with("refresh ") {
404                writeln!(&mut io::stdout(), "Getting process' information...");
405                if let Some(pid) = x
406                    .split(' ')
407                    .filter_map(|pid| pid.parse().ok())
408                    .take(1)
409                    .next()
410                {
411                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413                    } else {
414                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415                    }
416                } else {
417                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
418                }
419            } else {
420                writeln!(
421                    &mut io::stdout(),
422                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423                     list.",
424                );
425            }
426        }
427        "pid" => {
428            writeln!(
429                &mut io::stdout(),
430                "PID: {}",
431                sysinfo::get_current_pid().expect("failed to get PID")
432            );
433        }
434        "system" => {
435            writeln!(
436                &mut io::stdout(),
437                "System name:              {}\n\
438                 System kernel version:    {}\n\
439                 System OS version:        {}\n\
440                 System OS (long) version: {}\n\
441                 System host name:         {}",
442                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447            );
448        }
449        e => {
450            writeln!(
451                &mut io::stdout(),
452                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453                 list.",
454            );
455        }
456    }
457    false
458}
Source

pub fn transmitted(&self) -> u64

Returns the number of transmitted bytes since the last refresh.

If you want the total number of bytes transmitted, take a look at the total_transmitted method.

use sysinfo::Networks;
use std::{thread, time};

let mut networks = Networks::new_with_refreshed_list();
// Waiting a bit to get data from network...
thread::sleep(time::Duration::from_millis(10));
// Refreshing again to generate diff.
networks.refresh(true);

for (interface_name, network) in &networks {
    println!("out: {} B", network.transmitted());
}
Examples found in repository?
examples/simple.rs (line 316)
149fn interpret_input(
150    input: &str,
151    sys: &mut System,
152    networks: &mut Networks,
153    disks: &mut Disks,
154    components: &mut Components,
155    users: &mut Users,
156) -> bool {
157    match input.trim() {
158        "help" => print_help(),
159        "refresh_disks" => {
160            writeln!(&mut io::stdout(), "Refreshing disk list...");
161            disks.refresh(true);
162            writeln!(&mut io::stdout(), "Done.");
163        }
164        "refresh_users" => {
165            writeln!(&mut io::stdout(), "Refreshing user list...");
166            users.refresh();
167            writeln!(&mut io::stdout(), "Done.");
168        }
169        "refresh_networks" => {
170            writeln!(&mut io::stdout(), "Refreshing network list...");
171            networks.refresh(true);
172            writeln!(&mut io::stdout(), "Done.");
173        }
174        "refresh_components" => {
175            writeln!(&mut io::stdout(), "Refreshing component list...");
176            components.refresh(true);
177            writeln!(&mut io::stdout(), "Done.");
178        }
179        "refresh_cpu" => {
180            writeln!(&mut io::stdout(), "Refreshing CPUs...");
181            sys.refresh_cpu_all();
182            writeln!(&mut io::stdout(), "Done.");
183        }
184        "signals" => {
185            let mut nb = 1i32;
186
187            for sig in signals {
188                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189                nb += 1;
190            }
191        }
192        "cpus" => {
193            // Note: you should refresh a few times before using this, so that usage statistics
194            // can be ascertained
195            writeln!(
196                &mut io::stdout(),
197                "number of physical cores: {}",
198                sys.physical_core_count()
199                    .map(|c| c.to_string())
200                    .unwrap_or_else(|| "Unknown".to_owned()),
201            );
202            writeln!(
203                &mut io::stdout(),
204                "total CPU usage: {}%",
205                sys.global_cpu_usage(),
206            );
207            for cpu in sys.cpus() {
208                writeln!(&mut io::stdout(), "{cpu:?}");
209            }
210        }
211        "memory" => {
212            writeln!(
213                &mut io::stdout(),
214                "total memory:     {: >10} KB",
215                sys.total_memory() / 1_000
216            );
217            writeln!(
218                &mut io::stdout(),
219                "available memory: {: >10} KB",
220                sys.available_memory() / 1_000
221            );
222            writeln!(
223                &mut io::stdout(),
224                "used memory:      {: >10} KB",
225                sys.used_memory() / 1_000
226            );
227            writeln!(
228                &mut io::stdout(),
229                "total swap:       {: >10} KB",
230                sys.total_swap() / 1_000
231            );
232            writeln!(
233                &mut io::stdout(),
234                "used swap:        {: >10} KB",
235                sys.used_swap() / 1_000
236            );
237        }
238        "quit" | "exit" => return true,
239        "all" => {
240            for (pid, proc_) in sys.processes() {
241                writeln!(
242                    &mut io::stdout(),
243                    "{}:{} status={:?}",
244                    pid,
245                    proc_.name().to_string_lossy(),
246                    proc_.status()
247                );
248            }
249        }
250        "frequency" => {
251            for cpu in sys.cpus() {
252                writeln!(
253                    &mut io::stdout(),
254                    "[{}] {} MHz",
255                    cpu.name(),
256                    cpu.frequency(),
257                );
258            }
259        }
260        "vendor_id" => {
261            writeln!(
262                &mut io::stdout(),
263                "vendor ID: {}",
264                sys.cpus()[0].vendor_id()
265            );
266        }
267        "brand" => {
268            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269        }
270        "load_avg" => {
271            let load_avg = System::load_average();
272            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
273            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
274            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275        }
276        e if e.starts_with("show ") => {
277            let tmp: Vec<&str> = e.split(' ').collect();
278
279            if tmp.len() != 2 {
280                writeln!(
281                    &mut io::stdout(),
282                    "show command takes a pid or a name in parameter!"
283                );
284                writeln!(&mut io::stdout(), "example: show 1254");
285            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286                match sys.process(pid) {
287                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289                };
290            } else {
291                let proc_name = tmp[1];
292                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293                    writeln!(
294                        &mut io::stdout(),
295                        "==== {} ====",
296                        proc_.name().to_string_lossy()
297                    );
298                    writeln!(&mut io::stdout(), "{proc_:?}");
299                }
300            }
301        }
302        "temperature" => {
303            for component in components.iter() {
304                writeln!(&mut io::stdout(), "{component:?}");
305            }
306        }
307        "network" => {
308            for (interface_name, data) in networks.iter() {
309                writeln!(
310                    &mut io::stdout(),
311                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
312                    interface_name,
313                    data.mac_address(),
314                    data.received(),
315                    data.total_received(),
316                    data.transmitted(),
317                    data.total_transmitted(),
318                );
319            }
320        }
321        "show" => {
322            writeln!(
323                &mut io::stdout(),
324                "'show' command expects a pid number or a process name"
325            );
326        }
327        e if e.starts_with("kill ") => {
328            let tmp: Vec<&str> = e.split(' ').collect();
329
330            if tmp.len() != 3 {
331                writeln!(
332                    &mut io::stdout(),
333                    "kill command takes the pid and a signal number in parameter!"
334                );
335                writeln!(&mut io::stdout(), "example: kill 1254 9");
336            } else {
337                let pid = Pid::from_str(tmp[1]).unwrap();
338                let signal = i32::from_str(tmp[2]).unwrap();
339
340                if signal < 1 || signal > 31 {
341                    writeln!(
342                        &mut io::stdout(),
343                        "Signal must be between 0 and 32 ! See the signals list with the \
344                         signals command"
345                    );
346                } else {
347                    match sys.process(pid) {
348                        Some(p) => {
349                            if let Some(res) =
350                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
351                            {
352                                writeln!(&mut io::stdout(), "kill: {res}");
353                            } else {
354                                writeln!(
355                                    &mut io::stdout(),
356                                    "kill: signal not supported on this platform"
357                                );
358                            }
359                        }
360                        None => {
361                            writeln!(&mut io::stdout(), "pid not found");
362                        }
363                    };
364                }
365            }
366        }
367        "disks" => {
368            for disk in disks {
369                writeln!(&mut io::stdout(), "{disk:?}");
370            }
371        }
372        "users" => {
373            for user in users {
374                writeln!(
375                    &mut io::stdout(),
376                    "{:?} => {:?}",
377                    user.name(),
378                    user.groups()
379                );
380            }
381        }
382        "boot_time" => {
383            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384        }
385        "uptime" => {
386            let up = System::uptime();
387            let mut uptime = up;
388            let days = uptime / 86400;
389            uptime -= days * 86400;
390            let hours = uptime / 3600;
391            uptime -= hours * 3600;
392            let minutes = uptime / 60;
393            writeln!(
394                &mut io::stdout(),
395                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396            );
397        }
398        x if x.starts_with("refresh") => {
399            if x == "refresh" {
400                writeln!(&mut io::stdout(), "Getting processes' information...");
401                sys.refresh_all();
402                writeln!(&mut io::stdout(), "Done.");
403            } else if x.starts_with("refresh ") {
404                writeln!(&mut io::stdout(), "Getting process' information...");
405                if let Some(pid) = x
406                    .split(' ')
407                    .filter_map(|pid| pid.parse().ok())
408                    .take(1)
409                    .next()
410                {
411                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413                    } else {
414                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415                    }
416                } else {
417                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
418                }
419            } else {
420                writeln!(
421                    &mut io::stdout(),
422                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423                     list.",
424                );
425            }
426        }
427        "pid" => {
428            writeln!(
429                &mut io::stdout(),
430                "PID: {}",
431                sysinfo::get_current_pid().expect("failed to get PID")
432            );
433        }
434        "system" => {
435            writeln!(
436                &mut io::stdout(),
437                "System name:              {}\n\
438                 System kernel version:    {}\n\
439                 System OS version:        {}\n\
440                 System OS (long) version: {}\n\
441                 System host name:         {}",
442                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447            );
448        }
449        e => {
450            writeln!(
451                &mut io::stdout(),
452                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453                 list.",
454            );
455        }
456    }
457    false
458}
Source

pub fn total_transmitted(&self) -> u64

Returns the total number of transmitted bytes.

If you want the amount of transmitted bytes since the last refresh, take a look at the transmitted method.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("out: {} B", network.total_transmitted());
}
Examples found in repository?
examples/simple.rs (line 317)
149fn interpret_input(
150    input: &str,
151    sys: &mut System,
152    networks: &mut Networks,
153    disks: &mut Disks,
154    components: &mut Components,
155    users: &mut Users,
156) -> bool {
157    match input.trim() {
158        "help" => print_help(),
159        "refresh_disks" => {
160            writeln!(&mut io::stdout(), "Refreshing disk list...");
161            disks.refresh(true);
162            writeln!(&mut io::stdout(), "Done.");
163        }
164        "refresh_users" => {
165            writeln!(&mut io::stdout(), "Refreshing user list...");
166            users.refresh();
167            writeln!(&mut io::stdout(), "Done.");
168        }
169        "refresh_networks" => {
170            writeln!(&mut io::stdout(), "Refreshing network list...");
171            networks.refresh(true);
172            writeln!(&mut io::stdout(), "Done.");
173        }
174        "refresh_components" => {
175            writeln!(&mut io::stdout(), "Refreshing component list...");
176            components.refresh(true);
177            writeln!(&mut io::stdout(), "Done.");
178        }
179        "refresh_cpu" => {
180            writeln!(&mut io::stdout(), "Refreshing CPUs...");
181            sys.refresh_cpu_all();
182            writeln!(&mut io::stdout(), "Done.");
183        }
184        "signals" => {
185            let mut nb = 1i32;
186
187            for sig in signals {
188                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189                nb += 1;
190            }
191        }
192        "cpus" => {
193            // Note: you should refresh a few times before using this, so that usage statistics
194            // can be ascertained
195            writeln!(
196                &mut io::stdout(),
197                "number of physical cores: {}",
198                sys.physical_core_count()
199                    .map(|c| c.to_string())
200                    .unwrap_or_else(|| "Unknown".to_owned()),
201            );
202            writeln!(
203                &mut io::stdout(),
204                "total CPU usage: {}%",
205                sys.global_cpu_usage(),
206            );
207            for cpu in sys.cpus() {
208                writeln!(&mut io::stdout(), "{cpu:?}");
209            }
210        }
211        "memory" => {
212            writeln!(
213                &mut io::stdout(),
214                "total memory:     {: >10} KB",
215                sys.total_memory() / 1_000
216            );
217            writeln!(
218                &mut io::stdout(),
219                "available memory: {: >10} KB",
220                sys.available_memory() / 1_000
221            );
222            writeln!(
223                &mut io::stdout(),
224                "used memory:      {: >10} KB",
225                sys.used_memory() / 1_000
226            );
227            writeln!(
228                &mut io::stdout(),
229                "total swap:       {: >10} KB",
230                sys.total_swap() / 1_000
231            );
232            writeln!(
233                &mut io::stdout(),
234                "used swap:        {: >10} KB",
235                sys.used_swap() / 1_000
236            );
237        }
238        "quit" | "exit" => return true,
239        "all" => {
240            for (pid, proc_) in sys.processes() {
241                writeln!(
242                    &mut io::stdout(),
243                    "{}:{} status={:?}",
244                    pid,
245                    proc_.name().to_string_lossy(),
246                    proc_.status()
247                );
248            }
249        }
250        "frequency" => {
251            for cpu in sys.cpus() {
252                writeln!(
253                    &mut io::stdout(),
254                    "[{}] {} MHz",
255                    cpu.name(),
256                    cpu.frequency(),
257                );
258            }
259        }
260        "vendor_id" => {
261            writeln!(
262                &mut io::stdout(),
263                "vendor ID: {}",
264                sys.cpus()[0].vendor_id()
265            );
266        }
267        "brand" => {
268            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269        }
270        "load_avg" => {
271            let load_avg = System::load_average();
272            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
273            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
274            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275        }
276        e if e.starts_with("show ") => {
277            let tmp: Vec<&str> = e.split(' ').collect();
278
279            if tmp.len() != 2 {
280                writeln!(
281                    &mut io::stdout(),
282                    "show command takes a pid or a name in parameter!"
283                );
284                writeln!(&mut io::stdout(), "example: show 1254");
285            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286                match sys.process(pid) {
287                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289                };
290            } else {
291                let proc_name = tmp[1];
292                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293                    writeln!(
294                        &mut io::stdout(),
295                        "==== {} ====",
296                        proc_.name().to_string_lossy()
297                    );
298                    writeln!(&mut io::stdout(), "{proc_:?}");
299                }
300            }
301        }
302        "temperature" => {
303            for component in components.iter() {
304                writeln!(&mut io::stdout(), "{component:?}");
305            }
306        }
307        "network" => {
308            for (interface_name, data) in networks.iter() {
309                writeln!(
310                    &mut io::stdout(),
311                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
312                    interface_name,
313                    data.mac_address(),
314                    data.received(),
315                    data.total_received(),
316                    data.transmitted(),
317                    data.total_transmitted(),
318                );
319            }
320        }
321        "show" => {
322            writeln!(
323                &mut io::stdout(),
324                "'show' command expects a pid number or a process name"
325            );
326        }
327        e if e.starts_with("kill ") => {
328            let tmp: Vec<&str> = e.split(' ').collect();
329
330            if tmp.len() != 3 {
331                writeln!(
332                    &mut io::stdout(),
333                    "kill command takes the pid and a signal number in parameter!"
334                );
335                writeln!(&mut io::stdout(), "example: kill 1254 9");
336            } else {
337                let pid = Pid::from_str(tmp[1]).unwrap();
338                let signal = i32::from_str(tmp[2]).unwrap();
339
340                if signal < 1 || signal > 31 {
341                    writeln!(
342                        &mut io::stdout(),
343                        "Signal must be between 0 and 32 ! See the signals list with the \
344                         signals command"
345                    );
346                } else {
347                    match sys.process(pid) {
348                        Some(p) => {
349                            if let Some(res) =
350                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
351                            {
352                                writeln!(&mut io::stdout(), "kill: {res}");
353                            } else {
354                                writeln!(
355                                    &mut io::stdout(),
356                                    "kill: signal not supported on this platform"
357                                );
358                            }
359                        }
360                        None => {
361                            writeln!(&mut io::stdout(), "pid not found");
362                        }
363                    };
364                }
365            }
366        }
367        "disks" => {
368            for disk in disks {
369                writeln!(&mut io::stdout(), "{disk:?}");
370            }
371        }
372        "users" => {
373            for user in users {
374                writeln!(
375                    &mut io::stdout(),
376                    "{:?} => {:?}",
377                    user.name(),
378                    user.groups()
379                );
380            }
381        }
382        "boot_time" => {
383            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384        }
385        "uptime" => {
386            let up = System::uptime();
387            let mut uptime = up;
388            let days = uptime / 86400;
389            uptime -= days * 86400;
390            let hours = uptime / 3600;
391            uptime -= hours * 3600;
392            let minutes = uptime / 60;
393            writeln!(
394                &mut io::stdout(),
395                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396            );
397        }
398        x if x.starts_with("refresh") => {
399            if x == "refresh" {
400                writeln!(&mut io::stdout(), "Getting processes' information...");
401                sys.refresh_all();
402                writeln!(&mut io::stdout(), "Done.");
403            } else if x.starts_with("refresh ") {
404                writeln!(&mut io::stdout(), "Getting process' information...");
405                if let Some(pid) = x
406                    .split(' ')
407                    .filter_map(|pid| pid.parse().ok())
408                    .take(1)
409                    .next()
410                {
411                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413                    } else {
414                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415                    }
416                } else {
417                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
418                }
419            } else {
420                writeln!(
421                    &mut io::stdout(),
422                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423                     list.",
424                );
425            }
426        }
427        "pid" => {
428            writeln!(
429                &mut io::stdout(),
430                "PID: {}",
431                sysinfo::get_current_pid().expect("failed to get PID")
432            );
433        }
434        "system" => {
435            writeln!(
436                &mut io::stdout(),
437                "System name:              {}\n\
438                 System kernel version:    {}\n\
439                 System OS version:        {}\n\
440                 System OS (long) version: {}\n\
441                 System host name:         {}",
442                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447            );
448        }
449        e => {
450            writeln!(
451                &mut io::stdout(),
452                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453                 list.",
454            );
455        }
456    }
457    false
458}
Source

pub fn packets_received(&self) -> u64

Returns the number of incoming packets since the last refresh.

If you want the total number of packets received, take a look at the total_packets_received method.

use sysinfo::Networks;
use std::{thread, time};

let mut networks = Networks::new_with_refreshed_list();
// Waiting a bit to get data from network...
thread::sleep(time::Duration::from_millis(10));
// Refreshing again to generate diff.
networks.refresh(true);

for (interface_name, network) in &networks {
    println!("in: {}", network.packets_received());
}
Source

pub fn total_packets_received(&self) -> u64

Returns the total number of incoming packets.

If you want the amount of received packets since the last refresh, take a look at the packets_received method.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("in: {}", network.total_packets_received());
}
Source

pub fn packets_transmitted(&self) -> u64

Returns the number of outcoming packets since the last refresh.

If you want the total number of packets transmitted, take a look at the total_packets_transmitted method.

use sysinfo::Networks;
use std::{thread, time};

let mut networks = Networks::new_with_refreshed_list();
// Waiting a bit to get data from network...
thread::sleep(time::Duration::from_millis(10));
// Refreshing again to generate diff.
networks.refresh(true);

for (interface_name, network) in &networks {
    println!("out: {}", network.packets_transmitted());
}
Source

pub fn total_packets_transmitted(&self) -> u64

Returns the total number of outcoming packets.

If you want the amount of transmitted packets since the last refresh, take a look at the packets_transmitted method.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("out: {}", network.total_packets_transmitted());
}
Source

pub fn errors_on_received(&self) -> u64

Returns the number of incoming errors since the last refresh.

If you want the total number of errors on received packets, take a look at the total_errors_on_received method.

use sysinfo::Networks;
use std::{thread, time};

let mut networks = Networks::new_with_refreshed_list();
// Waiting a bit to get data from network...
thread::sleep(time::Duration::from_millis(10));
// Refreshing again to generate diff.
networks.refresh(true);

for (interface_name, network) in &networks {
    println!("in: {}", network.errors_on_received());
}
Source

pub fn total_errors_on_received(&self) -> u64

Returns the total number of incoming errors.

If you want the amount of errors on received packets since the last refresh, take a look at the errors_on_received method.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("in: {}", network.total_errors_on_received());
}
Source

pub fn errors_on_transmitted(&self) -> u64

Returns the number of outcoming errors since the last refresh.

If you want the total number of errors on transmitted packets, take a look at the total_errors_on_transmitted method.

use sysinfo::Networks;
use std::{thread, time};

let mut networks = Networks::new_with_refreshed_list();
// Waiting a bit to get data from network...
thread::sleep(time::Duration::from_millis(10));
// Refreshing again to generate diff.
networks.refresh(true);

for (interface_name, network) in &networks {
    println!("out: {}", network.errors_on_transmitted());
}
Source

pub fn total_errors_on_transmitted(&self) -> u64

Returns the total number of outcoming errors.

If you want the amount of errors on transmitted packets since the last refresh, take a look at the errors_on_transmitted method.

use sysinfo::Networks;

let networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("out: {}", network.total_errors_on_transmitted());
}
Source

pub fn mac_address(&self) -> MacAddr

Returns the MAC address associated to current interface.

use sysinfo::Networks;

let mut networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("MAC address: {}", network.mac_address());
}
Examples found in repository?
examples/simple.rs (line 313)
149fn interpret_input(
150    input: &str,
151    sys: &mut System,
152    networks: &mut Networks,
153    disks: &mut Disks,
154    components: &mut Components,
155    users: &mut Users,
156) -> bool {
157    match input.trim() {
158        "help" => print_help(),
159        "refresh_disks" => {
160            writeln!(&mut io::stdout(), "Refreshing disk list...");
161            disks.refresh(true);
162            writeln!(&mut io::stdout(), "Done.");
163        }
164        "refresh_users" => {
165            writeln!(&mut io::stdout(), "Refreshing user list...");
166            users.refresh();
167            writeln!(&mut io::stdout(), "Done.");
168        }
169        "refresh_networks" => {
170            writeln!(&mut io::stdout(), "Refreshing network list...");
171            networks.refresh(true);
172            writeln!(&mut io::stdout(), "Done.");
173        }
174        "refresh_components" => {
175            writeln!(&mut io::stdout(), "Refreshing component list...");
176            components.refresh(true);
177            writeln!(&mut io::stdout(), "Done.");
178        }
179        "refresh_cpu" => {
180            writeln!(&mut io::stdout(), "Refreshing CPUs...");
181            sys.refresh_cpu_all();
182            writeln!(&mut io::stdout(), "Done.");
183        }
184        "signals" => {
185            let mut nb = 1i32;
186
187            for sig in signals {
188                writeln!(&mut io::stdout(), "{nb:2}:{sig:?}");
189                nb += 1;
190            }
191        }
192        "cpus" => {
193            // Note: you should refresh a few times before using this, so that usage statistics
194            // can be ascertained
195            writeln!(
196                &mut io::stdout(),
197                "number of physical cores: {}",
198                sys.physical_core_count()
199                    .map(|c| c.to_string())
200                    .unwrap_or_else(|| "Unknown".to_owned()),
201            );
202            writeln!(
203                &mut io::stdout(),
204                "total CPU usage: {}%",
205                sys.global_cpu_usage(),
206            );
207            for cpu in sys.cpus() {
208                writeln!(&mut io::stdout(), "{cpu:?}");
209            }
210        }
211        "memory" => {
212            writeln!(
213                &mut io::stdout(),
214                "total memory:     {: >10} KB",
215                sys.total_memory() / 1_000
216            );
217            writeln!(
218                &mut io::stdout(),
219                "available memory: {: >10} KB",
220                sys.available_memory() / 1_000
221            );
222            writeln!(
223                &mut io::stdout(),
224                "used memory:      {: >10} KB",
225                sys.used_memory() / 1_000
226            );
227            writeln!(
228                &mut io::stdout(),
229                "total swap:       {: >10} KB",
230                sys.total_swap() / 1_000
231            );
232            writeln!(
233                &mut io::stdout(),
234                "used swap:        {: >10} KB",
235                sys.used_swap() / 1_000
236            );
237        }
238        "quit" | "exit" => return true,
239        "all" => {
240            for (pid, proc_) in sys.processes() {
241                writeln!(
242                    &mut io::stdout(),
243                    "{}:{} status={:?}",
244                    pid,
245                    proc_.name().to_string_lossy(),
246                    proc_.status()
247                );
248            }
249        }
250        "frequency" => {
251            for cpu in sys.cpus() {
252                writeln!(
253                    &mut io::stdout(),
254                    "[{}] {} MHz",
255                    cpu.name(),
256                    cpu.frequency(),
257                );
258            }
259        }
260        "vendor_id" => {
261            writeln!(
262                &mut io::stdout(),
263                "vendor ID: {}",
264                sys.cpus()[0].vendor_id()
265            );
266        }
267        "brand" => {
268            writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand());
269        }
270        "load_avg" => {
271            let load_avg = System::load_average();
272            writeln!(&mut io::stdout(), "one minute     : {}%", load_avg.one);
273            writeln!(&mut io::stdout(), "five minutes   : {}%", load_avg.five);
274            writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen);
275        }
276        e if e.starts_with("show ") => {
277            let tmp: Vec<&str> = e.split(' ').collect();
278
279            if tmp.len() != 2 {
280                writeln!(
281                    &mut io::stdout(),
282                    "show command takes a pid or a name in parameter!"
283                );
284                writeln!(&mut io::stdout(), "example: show 1254");
285            } else if let Ok(pid) = Pid::from_str(tmp[1]) {
286                match sys.process(pid) {
287                    Some(p) => writeln!(&mut io::stdout(), "{:?}", *p),
288                    None => writeln!(&mut io::stdout(), "pid \"{pid:?}\" not found"),
289                };
290            } else {
291                let proc_name = tmp[1];
292                for proc_ in sys.processes_by_name(proc_name.as_ref()) {
293                    writeln!(
294                        &mut io::stdout(),
295                        "==== {} ====",
296                        proc_.name().to_string_lossy()
297                    );
298                    writeln!(&mut io::stdout(), "{proc_:?}");
299                }
300            }
301        }
302        "temperature" => {
303            for component in components.iter() {
304                writeln!(&mut io::stdout(), "{component:?}");
305            }
306        }
307        "network" => {
308            for (interface_name, data) in networks.iter() {
309                writeln!(
310                    &mut io::stdout(),
311                    "{}:\n  ether {}\n  input data  (new / total): {} / {} B\n  output data (new / total): {} / {} B",
312                    interface_name,
313                    data.mac_address(),
314                    data.received(),
315                    data.total_received(),
316                    data.transmitted(),
317                    data.total_transmitted(),
318                );
319            }
320        }
321        "show" => {
322            writeln!(
323                &mut io::stdout(),
324                "'show' command expects a pid number or a process name"
325            );
326        }
327        e if e.starts_with("kill ") => {
328            let tmp: Vec<&str> = e.split(' ').collect();
329
330            if tmp.len() != 3 {
331                writeln!(
332                    &mut io::stdout(),
333                    "kill command takes the pid and a signal number in parameter!"
334                );
335                writeln!(&mut io::stdout(), "example: kill 1254 9");
336            } else {
337                let pid = Pid::from_str(tmp[1]).unwrap();
338                let signal = i32::from_str(tmp[2]).unwrap();
339
340                if signal < 1 || signal > 31 {
341                    writeln!(
342                        &mut io::stdout(),
343                        "Signal must be between 0 and 32 ! See the signals list with the \
344                         signals command"
345                    );
346                } else {
347                    match sys.process(pid) {
348                        Some(p) => {
349                            if let Some(res) =
350                                p.kill_with(*signals.get(signal as usize - 1).unwrap())
351                            {
352                                writeln!(&mut io::stdout(), "kill: {res}");
353                            } else {
354                                writeln!(
355                                    &mut io::stdout(),
356                                    "kill: signal not supported on this platform"
357                                );
358                            }
359                        }
360                        None => {
361                            writeln!(&mut io::stdout(), "pid not found");
362                        }
363                    };
364                }
365            }
366        }
367        "disks" => {
368            for disk in disks {
369                writeln!(&mut io::stdout(), "{disk:?}");
370            }
371        }
372        "users" => {
373            for user in users {
374                writeln!(
375                    &mut io::stdout(),
376                    "{:?} => {:?}",
377                    user.name(),
378                    user.groups()
379                );
380            }
381        }
382        "boot_time" => {
383            writeln!(&mut io::stdout(), "{} seconds", System::boot_time());
384        }
385        "uptime" => {
386            let up = System::uptime();
387            let mut uptime = up;
388            let days = uptime / 86400;
389            uptime -= days * 86400;
390            let hours = uptime / 3600;
391            uptime -= hours * 3600;
392            let minutes = uptime / 60;
393            writeln!(
394                &mut io::stdout(),
395                "{days} days {hours} hours {minutes} minutes ({up} seconds in total)",
396            );
397        }
398        x if x.starts_with("refresh") => {
399            if x == "refresh" {
400                writeln!(&mut io::stdout(), "Getting processes' information...");
401                sys.refresh_all();
402                writeln!(&mut io::stdout(), "Done.");
403            } else if x.starts_with("refresh ") {
404                writeln!(&mut io::stdout(), "Getting process' information...");
405                if let Some(pid) = x
406                    .split(' ')
407                    .filter_map(|pid| pid.parse().ok())
408                    .take(1)
409                    .next()
410                {
411                    if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 {
412                        writeln!(&mut io::stdout(), "Process `{pid}` updated successfully");
413                    } else {
414                        writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated...");
415                    }
416                } else {
417                    writeln!(&mut io::stdout(), "Invalid [pid] received...");
418                }
419            } else {
420                writeln!(
421                    &mut io::stdout(),
422                    "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \
423                     list.",
424                );
425            }
426        }
427        "pid" => {
428            writeln!(
429                &mut io::stdout(),
430                "PID: {}",
431                sysinfo::get_current_pid().expect("failed to get PID")
432            );
433        }
434        "system" => {
435            writeln!(
436                &mut io::stdout(),
437                "System name:              {}\n\
438                 System kernel version:    {}\n\
439                 System OS version:        {}\n\
440                 System OS (long) version: {}\n\
441                 System host name:         {}",
442                System::name().unwrap_or_else(|| "<unknown>".to_owned()),
443                System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
444                System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
445                System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
446                System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
447            );
448        }
449        e => {
450            writeln!(
451                &mut io::stdout(),
452                "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \
453                 list.",
454            );
455        }
456    }
457    false
458}
Source

pub fn ip_networks(&self) -> &[IpNetwork]

Returns the Ip Networks associated to current interface.

use sysinfo::Networks;

let mut networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("Ip Networks: {:?}", network.ip_networks());
}
Source

pub fn mtu(&self) -> u64

Returns the Maximum Transfer Unit (MTU) of the interface.

use sysinfo::Networks;

let mut networks = Networks::new_with_refreshed_list();
for (interface_name, network) in &networks {
    println!("mtu: {}", network.mtu());
}

Trait Implementations§

Source§

impl Debug for NetworkData

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Serialize for NetworkData

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for NetworkData

§

impl RefUnwindSafe for NetworkData

§

impl Send for NetworkData

§

impl Sync for NetworkData

§

impl Unpin for NetworkData

§

impl UnwindSafe for NetworkData

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of [From]<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.