有一个网络接口的文本文件:
auto eth0 bri0
iface eth0 inet static
address 192.168.1.118/24
iface eth0.110 inet manual
vlan-raw-device eth0
iface bri0 inet static
address 192.168.110.1/24
bridge_ports eth0.110
bridge_stp on
bridge_maxwait 10 ```
您需要从 eth0 获取地址并将其替换为另一个地址,例如 192.168.1.13。
我创建了一个获取所有接口和 ip 的类:
public class IpChangeService
{
private readonly string[] configFile;
private List<string> interfaceName = new List<string>();
private List<string> ipAddress = new List<string>();
private string currentAdapter;
public IpChangeService(string[] configFile, string currentAdapter)
{
this.configFile = configFile;
this.currentAdapter = currentAdapter;
}
public (IList<string> iface, IList<string> ipAddress) GetCurrentInterfaces()
{
foreach (var line in configFile)
{
if (line.Contains("iface") && line.Contains("inet static"))
{
if (interfaceName != null)
{
var str = line.Split(' ')[1] + " ";
var strWithoutSpaces = str.Replace(" ", "");
interfaceName.Add(strWithoutSpaces);
}
}
if (interfaceName!=null && line.Contains("address"))
{
// see http://stackoverflow.com/questions/4890789/regex-for-an-ip-address
ipAddress.Add(Regex.Match(line, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}").Value);
}
}
return (interfaceName, ipAddress);
}
public int GetCurrentInterfaceIndex()
{
return interfaceName.IndexOf(currentAdapter);
}
嗯,在主程序中我接收数据并尝试写下来,但是我觉得这样不正确,而且它不能正常工作(地址被歪斜插入)!而且我仍然不知道如何在没有通过索引硬编码的情况下正确选择 ip。
iface eth0 inet static
address 192.168.1.118/24168.1.13/24
private static void Main(string[] args)
{
var fileName = $"{AppDomain.CurrentDomain.BaseDirectory}interfaces";
var inputLines = File.ReadAllLines(fileName, Encoding.Default);
string interfaceName;
string ipAddress;
var ipChangeService = new IpChangeService(inputLines, "eth0");
var currentIface = ipChangeService.GetCurrentInterfaces();
var index = ipChangeService.GetCurrentInterfaceIndex();
interfaceName = currentIface.iface[index];
ipAddress = currentIface.ipAddress[0]; //FIXME: ХАРДКОД!
Console.WriteLine(interfaceName);
var s2 = "192.168.1.113/24"; // ip на который заменяем строчку
var configText = File.ReadAllText(fileName, Encoding.Default);
configText = configText
.Remove(configText.IndexOf(currentIface.ipAddress[0], StringComparison.Ordinal), ipAddress.Length)
.Insert(configText.IndexOf(currentIface.ipAddress[0], StringComparison.Ordinal), s2);
using (var file = new StreamWriter(fileName))
{
file.Write(configText);
}
Console.ReadKey();
}
但最重要的是,目前尚不清楚如何从所有现有的(可能有几个)中准确地选择 ip 地址 eth0。然后替换这个特定的子字符串。
试试这样:
在入口
在我们得到的输出
如果您只需要更换,那么您可以这样做:
我们制作了一个方法来搜索带有 Ip 的行:
我解释:
(значение, индекс)并仅采用具有address. 结果,我们将在列表中包含所有带有 ip 地址及其索引的行。for从带有 ip 的线路所在的位置运行到所需线路的循环即可。如果接口与我们要查找的接口匹配,则返回 ip 及其索引。然后一切都很简单:
我们从文件中逐行读取所有内容:
找到我们需要的ip:
更改该行中的 ip 地址:
好吧,它还有待保存:
结果: