Click here to Skip to main content
15,881,651 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi,
I have created a windows forms application with a text box for user to enter the port number onto which he wants to create a website. once the user enter the port number(as he wishes) and clicks on a button validation should be made to check in iis whether the port number is already used or not. If its already in use a messagebox should pop up showing an error message that port is already used by another site. I got some sample code from a forum but its not helping me out. Here is the code i have used but i am not able to do the validation.
try
 {
       string port = textBox2.Text;
       if (!Directory.Exists(port))
       {

         ServerManager serverManager = new ServerManager();
         Site site = serverManager.Sites.FirstOrDefault(s => s.Name == "Racing");
         SiteCollection coll = serverManager.Sites;

         foreach (Site indsite in coll)
         {
             Microsoft.Web.Administration.Binding binding = site.Bindings.Where(b => b.Protocol == "http").FirstOrDefault();
             MessageBox.Show(binding.BindingInformation.ToString());
         }
             MessageBox.Show("port number is valid");
       }
     else
     {
         MessageBox.Show("invalid");
     }
 }
 catch (Exception port)
 {
     MessageBox.Show(port.Message);
 }


Pls help me out as son as possible. Many Thanks in advance
Posted
Comments
Prasad Khandekar 15-Apr-13 7:18am    
You might find the answer to your query here (http://stackoverflow.com/questions/570098/in-c-how-to-check-if-a-tcp-port-is-available)
shivanand3291 15-Apr-13 7:54am    
Thanks prasad. iused this code from the link you hav posted. string hostname = "localhost";
int portno = 9081;
IPAddress ipa = (IPAddress) Dns.GetHostAddresses(hostname)[0];


try
{
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);
sock.Connect(ipa, portno);
if (sock.Connected == true) // Port is in use and connection is successful
MessageBox.Show("Port is Closed");
sock.Close();

}
catch (System.Net.Sockets.SocketException ex)
{
if (ex.ErrorCode == 10061) // Port is unused and could not establish connection
MessageBox.Show("Port is Open!");
else
MessageBox.Show(ex.Message);
but i am getting error in the 7th line as " This protocol version is not supported here" What can i do now? pls resolve this issue

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900