Take the 2-minute tour ×

If I have the following binary: <<"GET http://www.google.com HTTP/1.1">>, how can I split it up so that I can retrieve only the host (http://www.google.com) ?

I started with something like:

get_host(<<$G, Rest/binary>>) -> get_host(Rest);
get_host(<<$E, Rest/binary>>) -> get_host(Rest);
get_host(<<$T, Rest/binary>>) -> get_host(Rest);

but I am not sure how to go on from here. I was thinking of reversing Rest and starting over from the end of the binary.

share|improve this question
Well, why try? is it stream and not a fixed binary? (Like you don't now when the GET will show up). Otherwise split the binary. –  Jonke Mar 25 '11 at 10:58
@Jonke: it's actually the binary coming out of a browser's request; the above binary is only a small part of all the headers that a browser sends. –  hyperboreean Mar 25 '11 at 11:14

3 Answers 3

up vote 9 down vote accepted

It seems you're trying to implement a minimal parser for HTTP 1.1. This is one solution that does follow the specifications for HTTP 1.1 and parses the first line of a http request. Without knowing your specific situation I would in most cases recommend using a generic HTTP parser before a simplified "split binary" or similar.

1> erlang:decode_packet(http,<<"GET http://www.google.com HTTP/1.1\n">>,[]).  
share|improve this answer

I would recommend erlang:decode_packet for this, but to show how it can be done, here is a pair of functions that strips the leading "GET " and then returns everything up to the first space (but crashes if there is no space).

get_host(<<"GET ", Rest/binary>>) ->
    get_host2(Rest, <<>>).

get_host2(<<" ", _/binary>>, Acc) ->
get_host2(<<C, Rest/binary>>, Acc) ->
    get_host2(Rest, <<Acc/binary, C>>).

Basically, I put each byte that is not a space into my "accumulator", and when I find the space I return my accumulator. This is a common trick that is more often seen with lists. (With lists you will want to put new items at the front of the list and reverse the list at the end, to avoid your O(N) algorithm turning into O(N²), but that is not needed for binaries.)

share|improve this answer

The simple answer (but probably not what you really is asking for)

B = <<"GET http://www.google.com HTTP/1.1">> .
share|improve this answer

Your Answer


