2014-12-03 129 views
1

我在控制台应用程序简单的Web服务:获取Web服务客户端IP

static void Main(string[] args) 
     { 

      WSHttpBinding binding = new WSHttpBinding(); 
      binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; 
      binding.Security.Mode = SecurityMode.None; 

      Uri baseAddress = new Uri("http://localhost:8001/LogService"); 

      using (ServiceHost serviceHost = 
       new ServiceHost(typeof(MyLogService), baseAddress)) 
      { 
       // Check to see if it already has a ServiceMetadataBehavior 
       ServiceMetadataBehavior smb = 
        serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>(); 

       if (smb == null) 
        smb = new ServiceMetadataBehavior(); 

       smb.HttpGetEnabled = true; 
       smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy12; 
       serviceHost.Description.Behaviors.Add(smb); 

       // Add MEX endpoint 
       serviceHost.AddServiceEndpoint(
        ServiceMetadataBehavior.MexContractName, 
        MetadataExchangeBindings.CreateMexHttpBinding(), 
        "mex" 
        ); 

       serviceHost.AddServiceEndpoint(typeof(ILogService), binding, baseAddress); 


       serviceHost.Open(); 

       Console.WriteLine("The service is running. Press any key to stop."); 
       Console.ReadKey(); 
      } 


     } 

服务接口和类:

[ServiceContract] 
    interface ILogService 
    { 
     [OperationContract] 
     int LogIt(ref int id, string data, ref LogLevel level); 
    } 

    class MyLogService : ILogService 
    { 
     DBLogger dbl = new DBLogger(); 

     public int LogIt(ref int id, string data, ref LogLevel level) 
     { 
      try 
      { 

       String IP = HttpContext.Current.Request.UserHostAddress; 
       Console.WriteLine("conneted from host " + IP); 

      } 
      catch (Exception d) 
      { 
       Console.WriteLine(d.Message); 

      } 



      return 0; 
     } 
    } 

试图让客户端的IP一致:

String IP = HttpContext.Current.Request.UserHostAddress; 

CurrentNULL,我有例外。如何在我的项目案例中获取客户IP?

+0

要知道,一旦你有这方面的工作,这是这在本地网络中通常只会有用。当你在互联网上工作时,你不能(通常)得到客户的IP地址,也不应该尝试。不确定此警告是否适用于您的特定用途,但无论如何它值得添加。 – 2014-12-03 14:46:24

+0

我打算在互联网上运行此服务。你的意思是我不会在这种情况下获得客户IP地址?什么可能是解决方案? – vico 2014-12-03 14:55:10

+0

互联网上有很多IP流量可以通过的设备(路由器,网关,NAT设备,代理等),并且您的代码可以直接获取的唯一IP地址就是这些IP地址中最近的那个IP地址设备到您的机器。一些(如代理)*可能会添加额外的标头来指示原始IP地址(它们*可以获得),但是您必须相信该设备。 “解决方案”不是试图获取客户端的IP地址,而是为了解决*问题*,您认为获得该IP地址是解决方案的一部分。 – 2014-12-03 15:02:22

回答

0

因为您没有在ASP.NET模式下运行服务,所以不能使用HttpContext

试一下这个

MessageProperties props = OperationContext.Current.IncomingMessageProperties; 

RemoteEndpointMessageProperty prop = (RemoteEndpointMessageProperty)props[RemoteEndpointMessageProperty.Name]; 

string addr = prop.Address; 
int iPort = prop.Port; 
0

你的做法是对网络托管版本, 自托管尝试

object property; 
Request.Properties.TryGetValue(typeof(RemoteEndpointMessageProperty).FullName, out property); 
RemoteEndpointMessageProperty remoteProperty = property as RemoteEndpointMessageProperty; 

参考here的文档