[erlang-questions] subnet masking with binary matching

Robert Baruch autophile@REDACTED
Thu Jan 18 06:13:18 CET 2007


Binary matching is, inexplicably, covered in Programming Examples,  
the Bit Syntax chapter.

This works:

<<A:9, B:7>> = <<1,2>>.

A.
2
B.
2

This does not work:

<<A:9, B:8>> = <<1,2>>.

you get a badmatch.

So I suggest you do something like

Hostbits = 32 - Maskbits,
<<Subnet:Maskbits, _Host:Hostbits>> = B

--Rob

On Jan 18, 2007, at 12:03 AM, jm 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