public void ScanPort(string hostip,int startport,int endport) { for (int i = startport; i <= endport; i++) { lblMessage.Text = "Scanner: Scanning Port: " + i; Port = i;//Gets main IP of host System.Net.IPAddress ip = System.Net.Dns.GetHostEntry(hostip).AddressList[0]; IPEndPoint ipEnd = new IPEndPoint(ip, Port); //Creates a new socket. System.Net.Sockets.Socket _Sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp); try //Tests the port by trying to connect. { _Sock.Connect(ipEnd); } catch //Catches the error if it can not connect. { } if (_Sock.Connected == true) //Checks if socket is connected or not { listOpened.Items.Add(Port.ToString()); //Adds to opened list if socket connected listOpened.EnsureVisible(listOpened.Items.Count - 1); } else { listClosed.Items.Add(Port.ToString()); //Adds to Closed list if socket is not connected listClosed.EnsureVisible(listClosed.Items.Count - 1); } _Sock.Close(); //Close the socket } MessageBox.Show("All Ports Scanned Completed!", "", MessageBoxButtons.OK, MessageBoxIcon.Information); }