[erlang-questions] subnet masking with binary matching

Bob Ippolito bob@REDACTED
Thu Jan 18 06:33:28 CET 2007


There's plenty of documentation for all of Erlang's pattern matching
features in the reference manual.

You could just do this:

mask_address(Addr, Maskbits) ->
  B = list_to_binary(tuple_to_list(Addr)),
  io:format("address as binary: ~p ~p~n", [B,Maskbits]),
  Rest = (size(B) * 8) - Maskbits,
  <<Subnet:Maskbits, _Host:Rest>> = B,
  Subnet.

If/when the feature enhancements proposed in that paper end up in
Erlang, then this code would be shorter and cleaner. It sure would
make a huge difference in a lot of my code, but even the current
syntax is much better than bit twiddling other languages.

-bob

On 1/17/07, jm <jeffm@REDACTED> wrote:
> It's been pointed out to me that binary has to be a multiple of 8
> (thanks goes to Vance). So, the question now becomes is there an "erlang
> way" to do masking of IP addresses or should be done with a shift
> followed by an AND as I would do in C. Now I have an idea of why this
> broke I'll give it another go.
>
> Other than the "application...of bit stream programming in erlang" is
> there any documentation on the binary matching? I seem to remember
> seeing some somewhere, but I've looked around the erlang doc and seem to
> have missed it.
>
> Jeff.
>
> jm wrote:
> > Using binary matching to perform subnet masking with the following code,
> > which should work with both IPv4 and IPv6 as far as I can tell,
> >
> > mask_address(Addr, Maskbits) ->
> >    B = list_to_binary(tuple_to_list(Addr)),
> >    io:format("address as binary: ~p ~p~n", [B,Maskbits]),
> >    <<Subnet:Maskbits, _Host>> = B,
> >    Subnet.
> >
> > which errors with
> >
> > {badmatch,<<4 bytes>>}
> >
> > when called by
> >
> >    mask_address({192,168,1,128}, 25).
> >
> > yet works when called by
> >
> >    mask_address({192,168,1,0}, 24).
> >
> > Can anyone tell me how to fix this?
> >
> > Jeff.
> > _______________________________________________
> > erlang-questions mailing list
> > erlang-questions@REDACTED
> > http://www.erlang.org/mailman/listinfo/erlang-questions
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list