一键批量修改多网卡IP地址

因工作需要需要一键切换多网卡IP地址,网上找了半天没找到就自己使用C#语言生成指令后使用PowerShell进行设置,网卡名前缀是“port”,也可以改成其他名字的前缀,第一次发帖,各位大神不要见笑

// 验证IP合法性
if (ipParts.Length != 4 || !IPAddress.TryParse(inputIP, out _))
{
MessageBox.Show(“IP地址格式无效”);
return;
}
}
else
{
MessageBox.Show(“输入IP不能为空”);
return;
}

// 根据输入IP的最后一段确定port取值,取最后两位
string lastPart = ipParts[3];
if (lastPart.Length > 2)
{
lastPart = lastPart.Substring(lastPart.Length – 2);
}
if (!int.TryParse(lastPart, out int portCount))
{
MessageBox.Show(“末段值需为有效的整数”);
return;
}
// 验证末段值范围
if (portCount < 1 || portCount > 155)
{
MessageBox.Show(“末段值需在1~155之间”);
return;
}

// 拼接IP前缀
string ipPrefix = $”{ipParts[0]}.{ipParts[1]}.{ipParts[2]}”;
int startIP = 101;
StringBuilder commands = new StringBuilder();

// 生成命令
for (int i = 1; i <= portCount; i++)
{
int currentIP = startIP + i – 1;
commands.AppendLine($”netsh interface ip set address “port{i}” static {ipPrefix}.{currentIP} 255.255.255.0″);
}

textBox2.Text = commands.ToString();
}

private void ExecuteButton_Click(object sender, EventArgs e)
{
string commands = textBox2.Text.Trim();
if (string.IsNullOrEmpty(commands))
{
MessageBox.Show(“命令内容为空”);
return;
}

try
{
// 启动PowerShell进程并执行命令
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = “powershell.exe”,
Arguments = $”-NoProfile -ExecutionPolicy Bypass -Command “{commands}””,
UseShellExecute = true,
Verb = “runas” // 以管理员权限运行
};
Process.Start(psi);
}
catch (Exception ex)
{
MessageBox.Show($”执行失败: {ex.Message}”);
}
}

补充一下:如果需要设置40个网卡,列如需要改192.168.1.X段位的,只需填写192.168.1.140,由于IP是从101开始

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 共18条

请登录后发表评论