Re: CIDR Question: How to convert IP Address to CIDR Format

223 views
Skip to first unread message

Kirk Spessard

unread,
Apr 8, 2015, 6:40:41 PM4/8/15
to golan...@googlegroups.com
Or better example:

   ip := "1.2.3.4"
   mask := 24

And I want to convert this to....  "1.2.3.4/24"

On Wed, Apr 8, 2015 at 2:46 PM, <kspe...@google.com> wrote:
I have an IP address defined as a string and a CIDR based mask defined as an int.  What's the best way to convert the IP address to CIDR format?

For example:

     ip := "1.2.3.4"
     mask := 31

And I want to convert this to....  "1.2.3.4/31"

Kirk 

kspe...@google.com

unread,
Apr 8, 2015, 6:40:41 PM4/8/15
to golan...@googlegroups.com

David Anderson

unread,
Apr 8, 2015, 9:18:56 PM4/8/15
to Kirk Spessard, golang-nuts
cidr := &net.IPNet{net.ParseIP("1.2.3.4"), 24}
fmt.Println(cidr.String())

?

The function signatures are probably slightly wrong, but basically, assemble a net.IPNet by using net.ParseIP, then get the string. And if you have a CIDR network string, net.ParseCIDR will do the reverse.

- Dave

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages