private void updatePortItem(PortCheckItem portItemObj, bool isOpened) { if (isOpened) { portItemObj.Content = portItemObj.Result; portItemObj.ToolTip = portItemObj.Result; portItemObj.Background = new SolidColorBrush(Color.FromRgb(0, 240, 0)); } else { listBoxPortStatus.Items.Remove(portItemObj); } }
private void buttonScanStart_Click(object sender, RoutedEventArgs e) { listBoxPortStatus.Items.Clear(); string ipAddr = textBoxHostIP.Text; //Ping ping = new Ping(); //PingReply pingReply = ping.Send(ipAddr); //if (IPStatus.Success == pingReply.Status) //{ buttonScanStart.IsEnabled = false; buttonScanCancel.IsEnabled = true; List <PortCheckItem> portCheckLabelList = new List <PortCheckItem>(); int portNumStart = int.Parse(textBoxPortStart.Text); int portNumEnd = int.Parse(textBoxPortEnd.Text) + 1; for (int portNum = portNumStart; portNum < portNumEnd; portNum++) { PortCheckItem portLabelObj = new PortCheckItem(ipAddr, portNum); portCheckLabelList.Add(portLabelObj); } Task.Factory.StartNew(() => { ctsScan = new CancellationTokenSource(); TaskFactory tf = new TaskFactory(); List <Task> scanTaskArray = new List <Task>(); foreach (PortCheckItem portObj in portCheckLabelList) { Dispatcher.Invoke(new addListBoxItem(addPortItem), new object[] { portObj }); scanTaskArray.Add(Task.Run(() => scanPortOpen(portObj))); } tf.ContinueWhenAll(scanTaskArray.ToArray(), task => Dispatcher.Invoke(new taskEnd(scanPortFinished), new object[] { }), CancellationToken.None); }); //} //else //{ // listBoxPortStatus.Items.Add("Host [" + ipAddr + "] not available."); //} }
private void scanPortOpen(PortCheckItem portItem) { if (!ctsScan.IsCancellationRequested) { string ipAddress = portItem.IpAddress; int portNum = portItem.Port; string itemText = "Port [" + portNum.ToString() + "] N/A"; IPAddress ip = IPAddress.Parse(ipAddress); bool isOpened = false; try { IPEndPoint point = new IPEndPoint(ip, portNum); using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(point); socket.Close(); itemText = "Port [" + portNum.ToString() + "] " + getPortDesc(portNum); portItem.Result = itemText; isOpened = true; } } catch (SocketException ex) { itemText = "Port [" + portNum.ToString() + "] " + ex.Message; portItem.Result = itemText; } finally { Task.Run(() => Dispatcher.Invoke(new updateListBoxItem(updatePortItem), new object[] { portItem, isOpened })); } } else { string itemText = "Port [" + portItem.Port.ToString() + "] Cancelled."; portItem.Result = itemText; Task.Run(() => Dispatcher.Invoke(new updateListBoxItem(updatePortItem), new object[] { portItem, false })); } }
private void addPortItem(PortCheckItem portItem) { listBoxPortStatus.Items.Add(portItem); }