Using SQL to determine cidr value of a subnet mask

前端 未结 4 611
故里飘歌
故里飘歌 2021-02-05 21:56

I\'d like to find a way to do a SQL query that will calculate the cidr (bit representation) of a subnet mask stored in the database. So for example, I\'ve got either 255.255.25

4条回答
  •  囚心锁ツ
    2021-02-05 22:35

    e.g. you need to convert 255.255.255.252 netmask into bit mask.

    I always use this simple query (PostgreSQL) :

    SELECT 32-length(trim(((split_part('255.255.255.252','.',1)::bigint*(256^3)::bigint +
                            split_part('255.255.255.252','.',2)::bigint*(256^2)::bigint +
                            split_part('255.255.255.252','.',3)::bigint*256 +
                            split_part('255.255.255.252','.',4)::bigint)::bit(32))::text,'1'));
    

    not as nice as could be, but it's short and working like a charm..

提交回复
热议问题