Kevin Jensen
Kevin Jensen

Reputation: 1428

WCF: How to get Host IP or Server Name

I have a WCF service that is hosted via IIS on multiple web servers. I have a logging method that logs the calls to the database and I'd like to log which server the call is executing on.

Does anyone know how to get the host server name or IP address that the WCF call is executing on?

Upvotes: 16

Views: 19406

Answers (6)

Kolappan N
Kolappan N

Reputation: 4011

You can use the following code to get the current base address of server(host).

using System.ServiceModel;

var baseAddress = OperationContext.Current.Host.BaseAddresses[0].Authority;

Upvotes: 0

Dank
Dank

Reputation: 1

DNS host name doesn't work because many servers have multiple host names and you don't know which one the service was called on. IIRC, IIS can call differing web services based on which host name was specified making the matter worse. using .Current is great if you're not running a single instance, in which case you dont always have a non-null context object, which is my case for all of the above. If anyone has anything more solid, please share :)

Upvotes: 0

VdesmedT
VdesmedT

Reputation: 9113

Environment.MachineName 

does axactly that

Upvotes: 1

Dion
Dion

Reputation: 954

This is what worked for us. Make sure you have a reference to System.ServiceModel. Then implement the following code in your service method:

var context = System.ServiceModel.OperationContext.Current;

RemoteEndpointMessageProperty property = (RemoteEndpointMessageProperty)context.IncomingMessageProperties[RemoteEndpointMessageProperty.Name];

string externalIP = property.Address;

Upvotes: 6

Tomas Walek
Tomas Walek

Reputation: 2544

Use Dns.GetHostName(), because it's much better to get the name of the computer than the host IP. Consider the case when your host computer have more than one IP address, has virtual network cards (VMWare).

Upvotes: 15

Darren Kopp
Darren Kopp

Reputation: 77627

Dns.GetHostName() is what i use the most.

Upvotes: 1

Related Questions