title: How do I calculate the Network from an IP?
body: <p>I have the following IP address (example): <code>195.65.254.11</code></p>
  
  <p>I am looking to construct a set of queries (or functions) to return the network this IP belongs to (which is <code>195.65.254.0/24</code>)</p>
  
  <p>I started by converting the IP into a integer:</p>
  
  <pre><code>create function [dbo].[IPAddressToInteger] (@IP as varchar(15))
  returns bigint
  as
  begin
   return (convert(bigint, parsename(@IP,1)) +
           convert(bigint, parsename(@IP,2)) * 256 +
           convert(bigint, parsename(@IP,3)) * 256 * 256 +
           convert(bigint, parsename(@IP,4)) * 256 * 256 * 256)
  end
  
  select dbo.IPAddressToInteger('195.65.254.11'); -- 3275881995
  </code></pre>
  
  <p>Then I calculated the CIDR:</p>
  
  <pre><code>create function [dbo].[CIDRFromMask] (@mask as bigint)
  returns varchar(5)
  as
  begin
       declare @maskCalc bigint
       select  @maskCalc = dbo.IPAddressToInteger('255.255.255.255') - @mask + 1
  
       declare @logCalc int
       select  @logCalc = (32 - log(@maskCalc, 2))
  
       return '/' + cast(@logCalc as varchar(5))
  end
  
  select dbo.CIDRFromMask('3275881995'); -- /2
  </code></pre>
  
  <p>But here I am stuck. How do I continue to <strong>retrieve the correct network</strong>?</p>