我想使用C++读取和设置/ etc / network / interfaces中的所有参数。

这是我的接口(interface)文件

# /etc/network/interfaces

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
        address 192.168.1.6
        network 192.168.1.0
        netmask 255.255.255.0
        broadcast 192.168.1.255
        gateway 192.168.1.1
        hwaddress ether 50:76:A6:04:00:01

auto eth0:0
iface eth0:0 inet static
        address 100.100.100.251
        netmask 255.255.255.0

无论如何有做起来容易吗?

最佳答案

几天后,我得到了我问题的答案。

这个给你..

#include <iostream>
using std::cout;
using std::endl;

#include <fstream>
using std::ifstream;

#include <cstring>

const int MAX_CHARS_PER_LINE = 512;
const int MAX_TOKENS_PER_LINE = 20;
const char* const DELIMITER = " ";

int main()
{
  // create a file-reading object
  ifstream fin;
  fin.open("/etc/network/interfaces"); // open a file
  if (!fin.good())
    return 1; // exit if file not found

  // read each line of the file
  while (!fin.eof())
  {
    // read an entire line into memory
    char buf[MAX_CHARS_PER_LINE];
    fin.getline(buf, MAX_CHARS_PER_LINE);

    // parse the line into blank-delimited tokens
    int n = 0; // a for-loop index

    // array to store memory addresses of the tokens in buf
    const char* token[MAX_TOKENS_PER_LINE] = {}; // initialize to 0

    // parse the line
    token[0] = strtok(buf, DELIMITER); // first token

    if (token[0]) // zero if line is blank
    {
      for (n = 1; n < MAX_TOKENS_PER_LINE; n++)
      {
        token[n] = strtok(0, DELIMITER); // subsequent tokens

        if (!token[n])
          break; // no more tokens
      }
    }

    // process (print) the tokens
    for (int i = 0; i < n; i++) // n = #of tokens
    {
      if (strcmp (token[i],"\taddress") == 0 )
        cout << "IP: " << token[i+1] << endl;
      else if (strcmp (token[i],"\tnetwork") == 0 )
        cout << "NET: " << token[i+1] << endl;
      else if (strcmp (token[i],"\tnetmask") == 0 )
        cout << "MASK: " << token[i+1] << endl;
      else if (strcmp (token[i],"\tbroadcast") == 0 )
        cout << "BCAST: " << token[i+1] << endl;
      else if (strcmp (token[i],"\tgateway") == 0 )
        cout << "GTW: " << token[i+1] << endl;
      else if (strcmp (token[i],"\thwaddress") == 0 )
        cout << "MAC: " << token[i+2] << endl;

    }

    cout << endl;
  }
}

关于c++ - 如何在Linux网络接口(interface)文件(/etc/network/interfaces)上读取参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18337624/

10-09 05:21