Exemple #1
0
        public static bool CheckProcessByPort(int port)
        {
            if (port < 1024 && port > 49151)
            {
                return(false);
            }
            string        keyWord  = "LISTENING";
            string        command  = "netstat";
            string        argument = $" -nao";
            List <string> result   = ExecuteCommandAndGetOutput(command, argument);

            if (result.Count == 0)
            {
                return(false);
            }
            var line = result.FirstOrDefault(q => q.Contains(keyWord) && q.Contains(port.ToString()));

            if (line == null)
            {
                return(false);
            }
            int pid = TryConvert.String2Int(line.Substring(line.IndexOf(keyWord) + keyWord.Length).Trim());

            if (pid == 0)
            {
                return(false);
            }
            return(true);
        }
Exemple #2
0
        public static Process GetProcessByPort(int port)
        {
            if (port < 1024 && port > 49151)
            {
                return(null);
            }
            //if (Configuration.IsWindows)
            //{
            string        keyWord  = "LISTENING";
            string        command  = "netstat";
            string        argument = $" -nao";
            List <string> result   = ExecuteCommandAndGetOutput(command, argument);

            if (result.Count == 0)
            {
                return(null);
            }
            var line = result.FirstOrDefault(q => q.Contains(keyWord) && q.Contains(port.ToString()));

            if (line == null)
            {
                return(null);
            }
            int pid = TryConvert.String2Int(line.Substring(line.IndexOf(keyWord) + keyWord.Length).Trim());

            if (pid == 0)
            {
                return(null);
            }
            return(Process.GetProcessById(pid));
            //}
            //else
            //{
            //    string keyWord = "LISTEN";
            //    string command = "netstat";
            //    string argument = "-tnlp";
            //    List<string> result = ExecuteCommandAndGetOutput(command, argument);
            //    if (result.Count == 0)
            //        return null;
            //    var line = result.FirstOrDefault(q => q.Contains(keyWord) && q.Contains(port.ToString()));
            //    if (line == null)
            //        return null;
            //    string pidName = Utility.GetStringArrayValue(line, 6, " ");
            //    if (string.IsNullOrEmpty(pidName))
            //        return null;
            //    int pid = Utility.TryParseInt(pidName.Split("/").FirstOrDefault());
            //    if (pid == 0)
            //        return null;
            //    return Process.GetProcessById(pid);
            //}
        }