Skip to content

Instantly share code, notes, and snippets.

@geocar

geocar/a.erl Secret

Created Apr 15, 2019
Embed
What would you like to do?
-module(a).
-export([build/0, aton/1, bin/2, check/2]).
aton(I) -> {ok,{A,B,C,D}} = inet_parse:address(I), D + (C * 256) + (B * 65536) + (A * 16777216).
pair(X) -> [I,G] = binary:split(X, <<"/">>), N = binary_to_integer(G), IP = aton(binary_to_list(I)), {IP, IP + N}.
build() ->
{ok, T} = file:read_file("fullbogons-ipv4.txt"),
Lines = lists:filter(fun(X) -> X =/= <<>> end, tl(binary:split(T,<<"\n">>,[global]))),
lists:map(fun erlang:list_to_tuple/1, tuple_to_list(lists:unzip(lists:sort(lists:map(fun pair/1, Lines))))).
check(K,[A,B]) -> I = bin(A,K), element(I,A) =< K andalso element(I,B) >= K.
bin(A, Key) -> bin(A, Key, 1, tuple_size(A)).
bin(_, _, X, Y) when X > Y -> Y;
bin(A, K, X, Y) -> I = (Y + X) div 2, V = element(I, A), if K > V -> bin(A, K, I + 1, Y); K < V -> bin(A, K, X, I - 1); true -> I end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment