Permalink
Browse files

Favor existing address - bug 817

Added functionality in addr_util to get address lists and favor
current addresses.

Also added gangs of unit tests since I understand eunit now.

Change-Id: I273e67beadb10b0a394b67b862903747f8da356e
Reviewed-on: https://review.northscale.com:8443/1244
Reviewed-by: Steve Yen <steve.yen@gmail.com>
Tested-by: Dustin Sallings <dustin@spy.net>
  • Loading branch information...
dustin committed Mar 27, 2010
1 parent 5e33257 commit 46f656d2679bb188b6de18537d735380763372f6
Showing with 44 additions and 10 deletions.
  1. +43 −9 src/addr_util.erl
  2. +1 −1 src/net_watcher.erl
View
@@ -4,26 +4,60 @@
-module(addr_util).
--export([get_my_address/0]).
+-include_lib("eunit/include/eunit.hrl").
+
+-export([get_my_address/0, get_my_address/1]).
%% Find the best IP address we can find for the current host.
get_my_address() ->
+ get_my_address("255.255.255.255").
+
+get_my_address(CurrentAddress) ->
+ determine_address(CurrentAddress, list_all_addresses()).
+
+get_my_address_test() ->
+ %% Verify the result of this looks like an IP address.
+ 4 = length(string:tokens(get_my_address(), ".")).
+
+determine_address(CurrentAddress, AddrList) ->
+ case lists:member(CurrentAddress, AddrList) of
+ true -> CurrentAddress;
+ _ -> extract_addr(AddrList)
+ end.
+
+determine_address_test() ->
+ "4.1.1.1" = determine_address("255.255.255.255", ["4.1.1.1", "1.2.3.4"]),
+ "1.2.3.4" = determine_address("1.2.3.4", ["4.1.1.1", "1.2.3.4"]),
+ "127.0.0.1" = determine_address("1.2.3.4", []).
+
+list_all_addresses() ->
{ok, AddrInfo} = inet:getif(),
- Addr = extract_addr(
- lists:sort(
- lists:map(fun({A,_,_}) -> A end, AddrInfo))
- -- [{127,0,0,1}]), %% 127.0.0.1 is a special case.
- addr_to_s(Addr).
+ lists:sort(
+ lists:map(fun({A,_,_}) -> addr_to_s(A) end, AddrInfo)
+ -- ["127.0.0.1"]).
+
+list_all_addresses_test() ->
+ %% I can't test too much here since this isn't functional, but
+ %% I'll verify we go through the code and return something.
+ true = is_list(list_all_addresses()).
-%% [{1,2,3,4},...] -> {1,2,3,4}
+%% [X,...] -> X
extract_addr([H|_Tl]) ->
H;
-%% [] -> {127,0,0,1}
+%% [] -> "127.0.0.1"
extract_addr([]) ->
- {127,0,0,1}.
+ "127.0.0.1".
+
+extract_addr_test() ->
+ "4.1.1.1" = extract_addr(["4.1.1.1", "1.2.3.4"]),
+ "4.1.1.1" = extract_addr(["4.1.1.1"]),
+ "127.0.0.1" = extract_addr([]).
%% {1,2,3,4} -> "1.2.3.4"
addr_to_s(T) ->
string:join(lists:map(fun erlang:integer_to_list/1,
tuple_to_list(T)),
".").
+
+addr_to_s_test() ->
+ "1.2.3.4" = addr_to_s({1,2,3,4}).
View
@@ -30,7 +30,7 @@ handle_cast(Msg, _State) ->
handle_info(check_addr, State) ->
PrevAddr = State#state.current_address,
- case addr_util:get_my_address() of
+ case addr_util:get_my_address(PrevAddr) of
PrevAddr ->
{noreply, State};
NewAddress ->

0 comments on commit 46f656d

Please sign in to comment.