开发者

C# - Add and subtract from a IP address string to create a range

this is a slightly odd problem but I am looking for some c# code that will take a IP address provided as a string and return to me another 开发者_JAVA百科string which represents a IP address range that includes the initial IP address. For example...

If the initial string is "192.168.1.150" then I need to generate a new string that has the value "192.168.1.149-192.168.1.151".

I know I could achieve this by splitting the initial string at the "."'s and then converting the 4th number to a int and then subtracting or adding to it...but that seems a bit lame and I was hoping someone might have a more elegant solution :)

Also...i'd like this to support IPv6 addresses too.

Any cool methods? Thanks.


Honestly that sounds like the best way for IPv4. Get the fourth Octet (.150), cast to int, subtract 1 to get start of range, add one to get end of range. It doesn't get much simpler than that. As for IPv6, google "add hex numbers in c#".


In my opinion you must parse address to 4 byte type variables and add or subtract values to fourth of them. But you can put it in elegant class. which would support all IP Address related features in your app. In DDD this pattern is called Value-object.


Do you realize that what you asking for is impossible to do just from single IP address?
IP range you want to find depends on few parameters:

  • Network address
  • Broadcast address
  • Network mask

To actually retrieve network range the IP Address belongs to, you would need (if I recall correctly) at least two of them. Having network address and broadcast address, network range is obvious. Having network address and network mask, it could be computed. That should also be possible if you have IP address and network mask, but in such case you might end up with more than one possible solution (depending how other networks are split - they must fit the power of two, but...).

Therefore it is practically impossible to present you with such code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜