How to find the open and closed port list

In this article, I will explain how to find the open and closed port in the given ip address or host name.It is very simple and basic code.try to connect the socket.if it is connected port is opened otherwise port is closed.


this article is used to find the open and closed ports list of the user given ip address or host name.
here the scanport function have 3 parameters.first one is host name or ipaddress and second and third is starting,ending port numbers.
first try to connect the socket with ipaddress and port.
if the socket is connected then that port will be opened and that port is added into the openlist or otherwise closedlist.

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.
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);
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);


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: