Reputation: 29
In nodejs we have http.request(options[, callback]) with option localAddress ( Local interface to bind for network connections.). This is working pretty good. How can I implement this in Erlang? Now I use ibrowse for requests but this is not a constraint. I think I need to see how plain http in erlang works, but may be someone faced with this.
Upvotes: 1
Views: 288
Reputation: 13154
Basic TCP in Erlang provides an option for gen_tcp:connect/3,4 where you can declare a specific interface (or socket type, and a few other things).
If I only want to connect to some remote Host:Port the call looks like:
{ok, Socket} = gen_tcp:connect(Host, Port, [])
If I want the local side of the connection to originate from a specific address (on this machine 192.168.5.23 is wlan0, 192.168.7.67 is eth0, for example) I can do:
{ok, Socket} = gen_tcp:connect(Host, Port, [{ifaddr, {192,168,5,23}}])
If I want to connect from a specific port, I would add the port option:
Options = [{ifaddr, {192, 168, 5, 23}}, {port, 11311}],
{ok, Socket} = gen_tcp:connect(Host, Port, Options),
That's just vanilla TCP. Writing an HTTP/1.1 client in Erlang is pretty easy, and depending on what you want to do may be ideal.
There is also a built-in http client called httpc (and a few other somewhat more featureful/cleaner ones around like gun and hackney). These all make requests using similar arguments to gen_tcp, including availability of the same connect options as well as a special httpc:set_options/1,2 that is pretty straightforward to use:
ok = inets:start(),
ok = httpc:set_options([{ip, {192, 168, 5, 23}}, {port, 11311}]),
{ok, Response} = httpc:request("http://zxq9.com/archives/1311"),
Hopefully this is enough information to get you started.
Upvotes: 1