프로그램 제작 후 방화벽 때문에 허용되는 앱을 등록 할 떄가 있다.

방화벽에서 앱 허용.. 귀찮다.

매번 하기 귀찮아 방법을 찾아보았다.

코드로 가능한가 해서 찾아보니 요기잉네

https://csharp.hotexamples.com/examples/-/INetFwMgr/-/php-inetfwmgr-class-examples.html

 

아래 올려둔 코드는 해당 클래스를 static으로 변경해 놓은거다. 

AddProgram 함수도 쪼끔 바꿔놨으니 아래코드 가져다 쓰시면 된다.

 

일단 참조에 NetFwTypeLib을 추가해준다. 

참조추가

더보기

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetFwTypeLib;

public static class FirewallHandler
{
    #region Fields

        // ProgID for the AuthorizedApplication object
        private const string PROGID_AUTHORIZED_APPLICATION = "HNetCfg.FwAuthorizedApplication";
        private const string PROGID_OPEN_PORT = "HNetCfg.FWOpenPort";

        private static INetFwMgr _fwMgr;

        #endregion Fields

        #region Constructors


        #endregion Constructors

        #region Methods

        public static bool AddPort(string title, int portNo, bool isUDP)
        {
            bool result = false;
            INetFwOpenPort port = _GetPort(title, portNo, isUDP);
            INetFwMgr manager = _GetFirewallManager();
            try
            {
                manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port);
                result = true;
            }
            catch (Exception ex)
            {
                //MsgrLogger.WriteLog(ex.ToString());
            }
            return result;
        }
         /// <summary>
        /// 방화벽에 프로그램을 추가합니다.
        /// </summary>
        /// <param name="title">Application.ProductName + ".exe"</param>
        /// <param name="applicationPath">Application.ExecutablePath</param>
        /// <returns></returns>
        public static bool AddProgram(string title, string applicationPath)
        {
            bool exist = false;
            INetFwAuthorizedApplication auth = _GetAuth(title, applicationPath);

            _fwMgr = _GetFirewallManager();

            try
            {                               
                //           
                foreach (INetFwAuthorizedApplication mApp in _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)
                {
                    if (auth == mApp)
                    {
                        exist = true;
                        break;
                    }
                }
                if (!exist)
                {                    
                    _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
                    foreach (INetFwAuthorizedApplication mApp in _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)
                    {
                        if (auth == mApp)
                        {
                            exist = true;
                            break;
                        }
                    }
                }
                if (!exist)
                {
                    _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
                    foreach (INetFwAuthorizedApplication mApp in _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)
                    {
                        if (auth == mApp)
                        {
                            exist = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //MsgrLogger.WriteLog(ex.ToString());
            }
            return exist;
        }

        public static bool DisableFirewall()
        {
            return _SetEnableFirewall(false);
        }

        public static bool EnableFirewall()
        {
            return _SetEnableFirewall(true);
        }

        public static string GetByPort(int _port)
        {
            string portName = null;
            try
            {
                _fwMgr = _GetFirewallManager();
                foreach (INetFwOpenPort port in _fwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts)
                {
                    if (port.Port == _port)
                    {
                        portName = port.Name;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                //MsgrLogger.WriteLog(ex.ToString());
            }
            return portName;
        }

        public static string GetByProgramPath(string fileName)
        {
            string programName = null;
            try
            {
                _fwMgr = _GetFirewallManager();
                foreach (INetFwAuthorizedApplication app in _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)
                {
                    if (fileName.ToLower().Equals(app.ProcessImageFileName.ToLower()))
                    {
                        programName = string.Format("{0}[{1}]", app.Name, app.ProcessImageFileName);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                //MsgrLogger.WriteLog(ex.ToString());
            }
            return programName;
        }

        public static List GetPortList()
        {
            List aList = new List();
            try
            {
                _fwMgr = _GetFirewallManager();
                foreach (INetFwOpenPort port in _fwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts)
                {
                    aList.Add(port.Name + ":" + port.Port);
                }
            }
            catch (Exception ex)
            {
                //MsgrLogger.WriteLog(ex.ToString());
            }
            return aList;
        }

        public static List GetProgramList()
        {
            List aList = new List();
            try
            {
                _fwMgr = _GetFirewallManager();
                foreach (INetFwAuthorizedApplication app in _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications)
                {
                    aList.Add(app.Name + ":" + app.ProcessImageFileName);
                }
            }
            catch (Exception ex)
            {
                //MsgrLogger.WriteLog(ex.ToString());
            }
            return aList;
        }

        public static bool IsFirewallEnabled()
        {
            _fwMgr = _GetFirewallManager();

            return _fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled;
        }

        public static bool RemovePort(int portNo, bool isUDP)
        {
            bool result = false;
            INetFwMgr manager = _GetFirewallManager();
            NET_FW_IP_PROTOCOL_ protocol = isUDP ? NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP : NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            try
            {
                manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Remove(portNo, protocol);
                result = true;
            }
            catch (Exception ex)
            {
                //MsgrLogger.WriteLog(ex.ToString());
            }
            return result;
        }

        public static bool RemoveProgram(string applicationPath)
        {
            bool result = false;
            _fwMgr = _GetFirewallManager();

            try
            {
                _fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Remove(applicationPath);
                result = true;
            }
            catch (Exception ex)
            {
                //MsgrLogger.WriteLog(ex.ToString());
            }
            return result;
        }

        private static INetFwAuthorizedApplication _GetAuth(string title, string applicationPath)
        {
            // Create the type from prog id
            Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);
            INetFwAuthorizedApplication auth = Activator.CreateInstance(type)
                as INetFwAuthorizedApplication;
            auth.Name = title;
            auth.ProcessImageFileName = applicationPath;
            auth.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
            auth.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;
            auth.Enabled = true;

            return auth;
        }

        private static INetFwMgr _GetFirewallManager()
        {
            Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
            return (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
        }

        private static INetFwOpenPort _GetPort(string title, int portNo, bool isUDP)
        {
            Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT);
            INetFwOpenPort port = Activator.CreateInstance(type)
                as INetFwOpenPort;

            port.Name = title;
            port.Port = portNo;
            port.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
            port.Protocol = isUDP ? NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP : NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
            port.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;

            return port;
        }

        private static bool _SetEnableFirewall(bool enable)
        {
            _fwMgr = _GetFirewallManager();

            _fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled = enable;

            return _fwMgr.LocalPolicy.CurrentProfile.FirewallEnabled;
        }

        #endregion Methods
}

 

 

AddProgram 함수 사용하시면 된다.

+ Recent posts