Reputation: 13315
I need to get a tcp port of the specified web site on IIS 7 and IIS 6 using C#. I have a console application that knows the web site's name. It should find a port this web site is served on.
Upvotes: 3
Views: 3427
Reputation: 3979
FOR IIS 7 ;-)
private bool checkPortIsOpen(string portNumer)
{
ServerManager serverMgr = new ServerManager();
int index = 0;
bool isOpen = true;
foreach (Site mySite in serverMgr.Sites)
{
foreach (Microsoft.Web.Administration.ConfigurationElement binding in mySite.GetCollection("bindings"))
{
string protocol = (string)binding["protocol"];
string bindingInfo = (string)binding["bindingInformation"];
if (protocol.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
string[] parts = bindingInfo.Split(':');
if (parts.Length == 3)
{
string port = parts[1];
if(port.Equals(portNumer.ToString()))
{
isOpen = false;
webSite_portInUse = mySite.Name;
}
}
}
index++;
}
}
return isOpen;
}
Upvotes: 1
Reputation: 3218
Had to figure this out myself today, and got the answer I wanted, so figured I'd post it into this old thread.
You can determine the port by reading the IIS Metabase, which in IIS6 and above is an xml document.
In IIS6 get the file systemroot\system32\inetserv\metabase.xml and look at the node
/configuration/MBProperty/IIsWebServer[@ServerComment=$websitename]/serverBindings
In IIS7 get the file systemroot\system32\inetserv\config\applicationHost.config (it is xml, despite the .config extension) and look at the node /configuration/system.applicationHost/sites/site[@name='$websitename']
Upvotes: 0
Reputation: 13315
I think I can use System.DirectoryServices for IIS 6 and Microsoft.Web.Administration for IIS 7.
Upvotes: 2
Reputation: 1262
By default IIS binds to port 80 (default http port) but I am sure the answer is not that simple.
Maybe you could have used the admin scripts in IIS 6.0, to iterate through the IIS objects to find the port number, but this assumes the script is physically running on the server.
The only other option is run scan of each 65535 port to see if there a html listener using wget maybe.
Upvotes: 1
Reputation: 32380
OK. I'm going to give you a different answer since you commented that my last answer was not the answer to your question.
Try adding a global.asax
file to your asp.net application. It will have functions to handle different events on the server. For the Application_Start
function, you can have some code to save the port number that the web site is running on in a file or database somewhere.
Then, the console application can access the same file or database to find the port number.
If that doesn't suit you, then perhaps a better question to ask on SO would be "How can I programmatically read the IIS settings for a web site at run time?"
Upvotes: 1
Reputation: 366
you can get with servervariables Request.ServerVariables["SERVER_PORT"]
Upvotes: 4