Go Net Package Introduction

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Original link: http://blog.csdn.net/cc7756789w/article/details/51014076
Author: pastoral
Github:github.com/zhanghang-z
Reprint please indicate the source, not for commercial purposes without the author's permission.

Like most languages, Go's standard library is full, because Go's appearance is originally for the high Concurrency of network communication implementation, so its related network library encapsulates more concise, more readable.
Here to introduce a few network libraries, mastered the learning method, so long as there is that function, you can find and quickly read access to the source code, understand its implementation.

net.ResolveIPAddr()

Find IP addresses by domain name

Have to sigh go for developers to consider a lot, godoc this tool is really convenient! First look at the source code.

$ godoc -src net.ResolveIPAddr

funcRESOLVEIPADDR (NET, addrstring) (*IPADDR, error) {ifNET = =""{net ="IP"} afnet, _, Err: = Parsenetwork (NET)ifErr! =Nil{return Nil, err}Switchafnet { Case "IP","IP4","IP6":default:return Nil, Unknownnetworkerror (NET)} Addrs, err: = Internetaddrlist (afnet, addr, nodeadline)ifErr! =Nil{return Nil, err}returnAddrs.first (ISIPV4). (*IPADDR),Nil}

We also learned from the source of a trick: case "ip", "ip4", "ip6" . Switch is a case that detects multiple values directly and executes the code in default if they do not match.

You can see that both net and addr parameters accept the string type, and return the ipaddr pointer type, and the value of the error type.

To use:

package mainimport (    "fmt"    "net")func main() {    addr, err := net.ResolveIPAddr("ip""www.baidu.com")    ifnil {        fmt.Println(err)        os.Exit(1)    }    fmt.Println(addr.IP)

Output:

Pay attention to the source code of RESOLVEIPADDR, if you pass the parameter to net is not one "ip", "ip4", "ip6" of them, then err will not be nil, but UnknownNetworkError(net) , the error output information will be like this:
unknown network tcp

Net. Parseip ()

Check that the IP address format is valid

As usual, let's take a look at the source code $ godoc -src net ParseIP :

funcstring) IP {    for i := 0len(s); i++ {        switch s[i] {        case'.':            return parseIPv4(s)        case':':            false)            return ip        }    }    returnnil}

IPv4 . is separated by a number, IPv6 with a number, so the inside of this function is to determine whether it is IPv4 or IPv6.

Note: You do not manually call net.parseIPv4 or net.parseIPv6 , will report the following error:

cannot refer to unexported name net.parseIPV4undefined: net.parseIPV4

Because go uses the case of the first letter to restrict access outside the package, lowercase functions or variables cannot be accessed outside the package, just like the Java public,private modifier.

parseIPv4the source of the view also found:

funcstring) IP {    // ...    return IPv4(p[0], p[1], p[2], p[3])}

Go back toIPv4上

funcbyte) IP {    make(IP, IPv6len)    copy(p, v4InV6Prefix)    p[12] = a    p[13] = b    p[14] = c    p[15] = d    return p}

We find that these functions return IP objects, so let's look at the definition of an IP object:
type IP []byte
is actually a custom array slice type.

IPv4Internal with make Initializes an array slice and specifies the number of elements IPv6len . IPv6lenis defined as a constant:

const (    IPv6len = 16)

Then make a v4InV6Prefix copy to the array slice p , copy use your own search (note that copy behaves differently from ordinary people's understanding):

var v4InV6Prefix = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}

As for the array slices that store the IPv4, why would you assign 16 elements to the size, and then copy to the last four indexes to see type IP []byte the comments:

// An IP is a single IP address, a slice of bytes.// Functions in this package accept either 4-byte (IPv4)// or 16-byte (IPv6) slices as input.//// Note that in this documentation, referring to an// IP address as an IPv4 address or an IPv6 address// is a semantic property of the address, not just the// length of the byte slice: a 16-byte slice can still// be an IPv4 address.type IP []byte

That said, an 16-byte array of size can still be used as an IPv4 address. Create an array slice slice1 := make([]int, 5) whose initial value is 0.


Go source code is not difficult, even simpler than C, and the standard library design is very standardized. If you need to use more features, you can view the documentation for the net package.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.