net.DialIP laddr -- what is it, what's it for?

1,002 views
Skip to first unread message

Solar Granulation

unread,
May 6, 2015, 10:01:43 AM5/6/15
to golan...@googlegroups.com
Hello all, this is probably a very newbie question, as I'm very rusty and just getting back into some coding. I'm including some background so that my question has context.

Background:
I'm working my way through Network Programming with Go by Jan Newmarch and, among various issues with the code examples, ran into some confusion in 3.11 code example Ping where the variable addr is passed to net.DialIP twice, as both laddr and raddr.

addr, err := net.ResolveIPAddr("ip4", os.Args[1])
...
conn, err := net.DialIP("ip4:icmp", addr, addr)

I imagine it will come as no surprise to at least some of you that when using this code to dial localhost it works just fine, but trying to dial any other host results in errors (Cannot assign requested address). Since I didn't (and still don't) understand what laddr is doing I tried setting it to a resolved localhost, which gave me an "invalid parameter" error. Based on the documentation for DialTCP I tried nil, which works just fine and makes it possible to ping anywhere I like (within reason). So...

The question:
What, in the functions net.DialIP, net.DialTCP, and net.DialUDP, does the laddr parameter do? I know it's short for "local address", but what is the meaning of "local"? Is it an alias for the raddr, or is it supposed to be the IP address of the NIC? Is it something else entirely?

Thank you

Andy Balholm

unread,
May 6, 2015, 10:26:39 AM5/6/15
to Solar Granulation, golan...@googlegroups.com
> is it supposed to be the IP address of the NIC?

Yes, it tells which network interface to make the connection from.

James Bardin

unread,
May 6, 2015, 10:49:00 AM5/6/15
to golan...@googlegroups.com, solar.gr...@gmail.com


On Wednesday, May 6, 2015 at 10:26:39 AM UTC-4, Andy Balholm wrote:
> is it supposed to be the IP address of the NIC?

Yes, it tells which network interface to make the connection from.

Slight correction, it defines the local address to make the connection from. On Linux, the actual interface the packets leave on is determined via routing, unless you use a privileged call to set SO_BINDTODEVICE.

Doesn't usually make a difference, but there are always exceptions. 

Bhasker Hariharan

unread,
May 8, 2015, 12:21:21 AM5/8/15
to golan...@googlegroups.com
As others have said its the local address. Using Go's net/* this is the only way to bind a specific IP on a multihomed host for a given connection. Go doesn't expose a
bind() API in its net/* libraries.

Solar Granulation

unread,
May 11, 2015, 12:35:29 PM5/11/15
to golan...@googlegroups.com
Thanks, everyone. You've really helped.
Reply all
Reply to author
Forward
0 new messages