自己之前做过的WCF从来没有限制过IP的访问,今天就来做一个限制IP访问的WCF服务小例子。
首先我们创建一个控制台程序,添加契约接口和实现类,添加配置文件
契约接口代码:
using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; namespace ConsoleApplication1 { [ServiceContract] public interface IService { [OperationContract] string PrintTime(); } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.Configuration; namespace ConsoleApplication1 { public class Service:IService { public string PrintTime() { //获取远端信息 var ip = GetIpAddress(); if (!AllowConnect(ip)) { var msg = string.Format("IP:{0},不在允许的访问列表,禁止访问。", ip); Console.WriteLine(msg); throw new Exception(msg); } return DateTime.Now.ToString(); } private string GetIpAddress() { var remote = OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; return remote.Address; } public bool AllowConnect(string ip) { Tuple<long, long>[] m_IpRanges; var ipRange = ConfigurationManager.AppSettings["IpRangeFilter"]; string[] ipRangeArray; if (string.IsNullOrEmpty(ipRange) || (ipRangeArray = ipRange.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)).Length <= 0) { throw new ArgumentException("The ipRange doesn't exist in configuration!"); } m_IpRanges = new Tuple<long, long>[ipRangeArray.Length]; for (int i = 0; i < ipRangeArray.Length; i++) { var range = ipRangeArray[i]; m_IpRanges[i] = GenerateIpRange(range); } var ipValue = ConvertIpToLong(ip); var iplist = new System.Collections.Generic.List<long>(); for (var i = 0; i < m_IpRanges.Length; i++) { var range = m_IpRanges[i]; iplist.Add(range.Item1); iplist.Add(range.Item2); } iplist = iplist.OrderBy(a => a).ToList();//我这里认为,IP地址是成对出现的。那么,判断是否是符合标准的IP,则判断是否在范围内即可,或者范围外。 for (var i = 1; i <= iplist.Count; i += 2) { var item = iplist[i]; bool isodd = i % 2 == 1; if (isodd)//是奇数,代表是从列表的偶数位。1,3,5,7,9 { var last = iplist[i - 1]; if (last <= ipValue && item >= ipValue) return true; } } return false; } private Tuple<long, long> GenerateIpRange(string range) { var ipArray = range.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); if (ipArray.Length != 2) throw new ArgumentException("Invalid ipRange exist in configuration!"); return new Tuple<long, long>(ConvertIpToLong(ipArray[0]), ConvertIpToLong(ipArray[1])); } private long ConvertIpToLong(string ip) { var points = ip.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (points.Length != 4) throw new ArgumentException("Invalid ipRange exist in configuration!"); long value = 0; long unit = 1; for (int i = points.Length - 1; i >= 0; i--) { value += unit * Convert.ToInt32( points[i]); unit *= 256; } return value; } } }
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <behaviors> <endpointBehaviors> <behavior name="webBehavior"> <!--这里必须设置--> <!--<webHttp />--> <enableWebScript /> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="metadataBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://192.168.1.112:8890/Service/metadata" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="metadataBehavior" name="ConsoleApplication1.Service"> <endpoint address="http://192.168.1.112:8890/Service" binding="wsHttpBinding" bindingConfiguration="wsBinding" contract="ConsoleApplication1.IService" /> </service> </services> <bindings> <wsHttpBinding> <binding name="wsBinding"> <security mode="None"/> </binding> </wsHttpBinding> </bindings> </system.serviceModel> <appSettings> <add key="IpRangeFilter" value="192.168.1.113-192.168.1.115"/> </appSettings> </configuration>
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(ConsoleApplication1.Service))) { host.Opened += delegate { Console.WriteLine("服务已经启动,按任意键终止服务!"); }; host.Open(); Console.Read(); } } } }
启动我们的WCF服务!
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { ServiceReference1.ServiceClient service = new ServiceReference1.ServiceClient(); label1.Text=service.PrintTime(); } } }
点击按钮调用我们的WCF服务,会提示这样的错误!
再看看我们的WCF服务的提示:
你们的WCF是不是所有的IP都能访问呢?