Luckily, you have some options.
1) Pass the IP address as a parameter --> NOT recommended.
2) Create a SOAP header for the IP Address and pass it from the client
I wrote you a quick sample for option 2.
First, you need to extend SoapHeader and create a class to pass the IP Address.
using System.Web.Services.Protocols;
namespace SoapHeaders
{
public class IpAddressHeader : SoapHeader
{
public string IpAddress;
}
}
Next, you need to define a web service with that header, and a web method that uses it.
using System;
using System.IO;
using System.Web.Services.Protocols;
using System.Web.Services;
using SoapHeaders;
namespace WebService
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class SoapHeaderService : System.Web.Services.WebService
{
public IpAddressHeader IpAddressHeader;
[WebMethod]
[SoapDocumentMethod(OneWay = true)]
[SoapHeader("IpAddressHeader")]
public void LogIpAddress()
{
var logFile = string.Format(@"C:\Logs\{0:yyyy-MM-dd HH.mm.ss.ffff}.log", DateTime.Now);
string ipAddress;
if (IpAddressHeader == null || string.IsNullOrEmpty(IpAddressHeader.IpAddress))
{
ipAddress = "?";
}
else
{
ipAddress = IpAddressHeader.IpAddress;
}
File.WriteAllText(logFile, string.Format("Client Address --> {0}", ipAddress));
}
}
}
Finally, you need a client to consume the service and pass the header information. I just made a quick console application, but it could be anything, really:
using System.Net;
using ConsoleApplication.soapHeaderServices;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var ipAddressHeader = new IpAddressHeader();
ipAddressHeader.IpAddress = GetIpAddress();
var serviceClient = new SoapHeaderService();
serviceClient.IpAddressHeaderValue = ipAddressHeader;
serviceClient.LogIpAddress();
}
static string GetIpAddress()
{
var ipAddress = "?";
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var address in host.AddressList)
{
if (address.AddressFamily.ToString() != "InterNetwork")
{
continue;
}
ipAddress = address.ToString();
break;
}
return ipAddress;
}
}
}
I deployed the service on a remote test service and called it from my PC. Works fine. Contents of the log file created: Client Address --> 192.168.1.41
I hope you find that helpful!
EDIT: DO NOT USE MY BELOW CODE. It is wrong. I'm leaving it as an example of what NOT to do.
Server variables are not available in one-way operations.
ORIGINAL ANSWER. DO NOTE USE: See my updated answer above the EDIT.
I just smoke tested this on a new ASP.Net Web Service Application. Works from every endpoint I have access to.
HttpRequest.UserHostAddress is the document way to get the client's IP address. If that is not working for you, I would look for underlying causes.
[WebMethod]
[SoapDocumentMethod(OneWay = true)]
public void Silent()
{
var address = HttpContext.Current.Request.UserHostAddress;
// Do something with address
Trace.Write(address);
}