C#中的IP范围控制? [英] Ip Range Control in c# ?

查看:73
本文介绍了C#中的IP范围控制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我应该控制用户的IP地址是否在IP范围内.

我为此写了一个函数,我控制ip地址块.首先我控制ip地址小于ip range的上限.
当它控制IP地址的第一个块时,第一个IP地址块仍然存在,但是它将第二个IP地址作为上限IP地址.

Hi all,
I should make control of user''s ip adress is in an ip range or not.

I wrote a function for that , I control the ip adress blocks .Firstly I control the ip adress is smaller than ip range''s upper limit.
When it controls the first blocks of ip adresses , the first block of ip adress remains, but it takes the second block in the upper limit ip adress.

 public bool isInIpRange(string ipAdress, string ipFrom, string ipTo)
        {
            string[] ipAddr = ipAdress.Split('.');
            string[] ipFromAddr = ipFrom.Split('.');
            string[] ipToAddr = ipTo.Split('.');
            int ValidBlock = 0;

 foreach (var ipBlock in ipAddr)
             {
                int ipValue = Convert.ToInt32(ipBlock);

                foreach (var ipToBlock in ipToAddr)
                {
                    int ipToValue = Convert.ToInt32(ipToBlock );

                    if (ipValue <= ipToValue)
                    {
                        ValidBlock++;
                    }
                }
            }
            if (ValidBlock == 4)
            {
                return true;
            }
            else
            {
                return false;
            }
}


我想将1.块控制为1.块2.阻止到2.阻止.和4.阻止到4.阻止.
但是在内部预测中,它控制1. ip地址块到所有上限ip地址块.


我该如何解决?
感谢您的提前答复.


I want to control 1. block to 1. block.2. block to 2. block .and 4. block to 4. block.
But at inner foreeach , it controls 1. block of ip adresses to all blocks of upper limit ip adress.


How can I resolve this ?
Thanks for your replies in advance.

推荐答案

no _-_ namee442,

考虑使用正则表达式,例如"\ b \ d {1,3} \.\ d {1,3} \.\ d {1,3} \.\ d {1,3} \ b"来获取四个IP地址的编号.

no_-_namee442,

Consider using a Regular Expression like "\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b" to get the four numbers of the IP address.

Regex findIPV4Parts= new Regex(@"(?<octet1>\b\d{1,3})\.(?<octet2>\d{1,3})\.(?<octet3>\d{1,3})\.(?<octet4>\d{1,3})\b", RegexOptions.Singleline);
Match match = findIPV4Parts.Match(ipv4Data);
//From here, you can deal with each octet individually.
string firstOctet = match.Groups["Octet1"].Value;



使用提供的正则表达式代码,您可以轻松访问IP地址的每个部分.然后,您可以验证每个部分并返回更具体的用户反馈.请注意,这仅适用于IPV4地址.

霍根



With the regex code provided, you have easy access to each part of the IP address. Then you can validate each part and return more specific user feedback. Please note that this only works on IPV4 addresses.

Hogan


这篇关于C#中的IP范围控制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆