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

3次阅读
没有评论

因工作需要需要一键切换多网卡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开始

正文完
 0
116博客
版权声明:本篇文章由 116博客 于2025-04-01发表,共计1358字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码