有相关帖子将CIDR符号转换为IP范围。我需要反过来。如果可能的话,我需要压缩大量的IP到CIDR表示法。
输入示例:
192.168.0.0
192.168.0.1
..
..
192.168.0.255
192.168.2.4
192.168.3.8
输出示例:
192.168.0/24
192.168.2.4
192.168.3.8
因为192.168.2.4和192.168.3.8不能用CIDR表示法表示,所以它可以按原样列出。
我知道这很难。因为CIDR表示法具有不同的块大小。但至少如何用C块压缩我的列表(256个IP)?
我会尝试使用C#linq。
答案 0 :(得分:0)
我想象没有编码很难做到。这是我尝试编写CidrCompressor。为每个IP调用Add(),然后使用IpList属性获取压缩列表。
class Api::V1::SfdcsController < ApplicationController
include Databasedotcom::Rails::Controller
def getSfdcauthentication
username = params[:username]
password = params[:password]
client_id = params[:client_id]
client_secret = params[:client_secret]
client = Databasedotcom::Client.new :client_id => client_id, :client_secret => client_secret
begin
oauth_token = client.authenticate :username => username, :password => password #=> "the-oauth-token"
rescue =>e
oauth_token = false
end
if oauth_token
contact_class = client.materialize("Contact")
@sf_contacts = Contact.all
respond_with(@sf_contacts) do |format|
format.json { render :json => @sf_contacts.as_json }
end
else
render json: {status:200,message:"Authentication failed"}
end
end
end
答案 1 :(得分:0)
我找到了C块CIDR表示法的解决方案,但它适用于 ONLY C block 。不适用于所有街区。
public static List<string> IpListToCIDR(List<string> ipList)
{
//Suanda sadece C blok icin yazilmistir. Ileride gelistirilebilir
//result list
List<string> compressedList = new List<string>();
//group ip addresses
var cidrList = ipList.GroupBy(o => new
{
GrpKey = o.Substring(0, o.LastIndexOf('.'))
})
.Select(g => new
{
IpSubnet = g.Key.GrpKey,
Count = g.Count()
})
.Where(m => m.Count >= 255)
.ToList();
//exclude grouped list
var excludeList = (from a in ipList
join c in cidrList on a.Substring(0, a.LastIndexOf('.')) equals c.IpSubnet
select a).ToList();
//add C block CIDR list
compressedList.AddRange(cidrList.Select(m => m.IpSubnet + ".0/24").ToList());
//add rest of them
compressedList.AddRange(ipList.Where(m=> !excludeList.Contains(m)).ToList());
return compressedList;
}