You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修复C++白名单防火墙程序的getline、ostringstream及Netsh规则错误

修复白名单防火墙程序的两类问题

问题分析与修复方案

1. getline与ostringstream的使用错误

原代码中ostringstream的初始化逻辑完全错误:用Name或Directory作为流的初始内容,后续追加命令时会生成名称+命令的无效格式;同时若输入的名称或路径包含空格,netsh会将其解析为多个参数导致执行失败。

2. Netsh命令报错解决

报错"One or more of the specified profiles is not valid. 'Any' cannot be specified if other profiles are specified."是因为默认情况下netsh在网络配置文件(profile)的选择上存在冲突,显式指定profile=any即可消除该问题。

修复后的完整代码

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
start:
    system("title WHITELIST FIREWALL");
    FILE* codefile;
    // 优化文件存在性检查的写法,避免歧义
    if ((codefile = fopen("C:\\Windows\\disable.dl", "r")) != NULL) {
        fclose(codefile);
        goto no;
    }
    else {
        goto firewall;
    }

no:
    system("cls");
    system("echo Please Turn On Firewall Filter First");
    system("pause");
    goto start;

firewall:
    std::string Name;
    std::string Directory;
    system("cls");
    
    cout << "Name: ";
    getline(cin, Name);
    cout << "Directory Application: ";
    getline(cin, Directory);

    // 创建空的ostringstream,避免初始值干扰命令拼接
    std::ostringstream oss_in;
    std::ostringstream oss_out;

    // 用双引号包裹含空格的参数,添加profile=any解决配置文件冲突
    oss_in << "netsh advfirewall firewall add rule name=\"" << Name 
           << "\" dir=in action=allow program=\"" << Directory 
           << "\" enable=yes profile=any";
    system(oss_in.str().c_str());

    oss_out << "netsh advfirewall firewall add rule name=\"" << Name 
            << "\" dir=out action=allow program=\"" << Directory 
            << "\" enable=yes profile=any";
    system(oss_out.str().c_str());

    system("del C:\\Windows\\rules.wfw");
    system("netsh advfirewall export C:\\Windows\\rules.wfw");
    system("pause");
    return 0;
}

关键修复点说明

  • ostringstream初始化修正:改为创建空流,确保命令从netsh开头正确拼接。
  • 参数引号包裹:对name和program参数添加双引号,兼容含空格的名称或路径输入。
  • 添加profile=any参数:显式指定规则应用到所有网络配置文件,解决原报错问题。
  • 文件检查写法优化:明确判断文件指针是否非空,提升代码可读性。

内容的提问来源于stack exchange,提问作者ANONIMUS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:45:38