Golang in net package usage (i)

Source: Internet
Author: User
Tags parse error domain name server mail exchange mx record subdomain subdomain name
This is a creation in Article, where the information may have evolved or changed.

NET package provides a portable interface for network I/O, including TCP/IP,UDP, domain name resolution, and UNIX sockets. Although the net package provides a lot of access to the underlying interfaces, in most cases the client only needs the most basic interfaces, such as DIAL,LISTEN,ACCEPTE and the assigned Conn connection and listener interface. The CRYPTO/TLS package uses the same interface and similar dial and listen functions. The net package is analyzed in detail below.

The constants are described first:

Const (
 Ipv4len = 4
 Ipv6len = 16
It is easy to see that this represents the length of the IP address (bytes), where IPv4 length is 4,ipv6 address length is 16


Common IPv4 Address:

Var (
     IPv4bcast = IPv4(255, 255, 255, 255) // broadcast address
     IPv4allsys = IPv4(224, 0, 0, 1) // All systems, including hosts and routers, this is a multicast address
     IPv4allrouter = IPv4(224, 0, 0, 2) // All multicast routers
     IPv4zero = IPv4(0, 0, 0, 0) // Local network, only as a local source address, it is legal

Common IPV6 Address:

var (
    IPv6zero                   = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}     
    IPv6unspecified            = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    IPv6loopback               = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
    IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
    IPv6linklocalallnodes      = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
    IPv6linklocalallrouters    = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02}

Next talk about IPV4 and IPV6 related knowledge, understand please skip directly.

The IP address (the InternetProtocoladdress, known as the Internet Protocol addresses), is a way of addressing the host on the Internet. The common IP address is divided into IPV4 and IPV6 address two categories.

The IPV4 is represented by a 32-bit binary number, It is represented as XXX.XXX.XXX.XXX, each group of XXX represents 10 binary numbers less than or equal to 255, and the total number of IPV4 addresses is 232, however, some addresses are reserved for special purposes, such as private networks (about 18 million addresses) and multicast addresses (about 270 million addresses). IPV4 is divided into ABCDE five types of addresses, respectively, to introduce:

Class A address The first bit is 0, the attention is bit 1, the 1th byte is the network address, the other 3 bytes is the host address 

2, the address range:

3, 10.x.x.x is the private address, the range from

4, 127.x.x. X is a reserved address and is used as a loopback test. 

Class B Address First two bits is 10, note is bit 1, the 1th byte and the 2nd byte are the network address, the latter 2 bytes is the host address 

2, the address range:

3, the private address range:

4, Reserved address: 169.254.x.x 

Class C Address First three bits is 110, note is bit 1, the first three bytes is the network address, the last byte is host address 

2, address range:

3, private address: 192.168.x.x, range from

Class D address First four bits is 1110, note three bit 1, no network address and host address. 

2, Address range:

Class E address First five bits is 11110, note four bit 1, no network address and host address 

2, address range: 

In addition there are several special IP addresses: 1, can only do the source address 

2, is broadcast address 

3, 127. x.x.x for loopback address, native use 

4, private address: 

10/8 address range:,

172.16/12 address range:,

192.168/ 16 address range: 

multicast address, note the difference between it and broadcast. This is the address from to refers specifically to all hosts and routers, specifically all Routers。 Such addresses are used in a number of specific programs and multimedia programs. If your host has the IRDP (Internet routing discovery, use multicast feature) feature, you should have such a route in your host routing table. 


If your host uses DHCP to automatically obtain an IP address, your DHCP server fails, or the response time is too long to exceed a systemThe wingdows system will assign you such an address at a specified time. If you find that your host IP address is a sort of address, unfortunately, it is possible that your network is not functioning properly.

For unicast broadcasts and multicast introductions and their pros and cons, check out this article: Http://www.h3c.com.cn/products___technology/technology/group_management/other_ Technology/technology_recommend/200805/605846_30003_0.htm

Since the IPV4 address has 232 addresses, about 4.3 billion, resulting in its insufficient use, resulting in a Ipv6,ipv6 address length of 128 bits, the total number of addresses is 2,128, IPV6 solve the problem of IPV4 address is not enough, IPV6 more detailed introduction please refer to/HTTP Zh.wikipedia.org/wiki/ipv6

Func Interfaceaddrs () ([]addr, error)//interfaceaddrs returns the address list of the system's network interface.

Func Interfaces () ([]interface, error)//interfaces returns a list of network interfaces for the system.

Func Joinhostport (host, port string) string//joinhostport merges host and port into one network address. The general format is "Host:port", and if host contains a colon or percent semicolon, the format is "[Host]:p ort".

Func lookupaddr (addr string) (name []string, err Error)//reverse-lookup for a given address and return a list of lists mapped to that address
Func lookupcname (name string) (CNAME string, err Error)//returns the DNS host name of the specification for the given name, and if the caller does not care if the name is canonical, it can be called directly lookuphost or LOOKUPIP, both functions will take into account the canonical name when querying.
Func lookuphost (Host string) (Addrs []string, err Error)//Returns an array of host addresses by using the local parser to find the given host
Func Lookupip (Host string) (Addrs []ip, err Error)//Returns an array of host IPv4 and IPv6 addresses by locating host with the local parser

Examples of how to use it:

Package main

Import (

Func main() {
Addr, _ := net.InterfaceAddrs()
fmt.Println(addr) //[ ::1/128 fe80::3617:ebff:febe:f123/64], local address, ipv4 and ipv6 address, this information can be passed Ifconfig command to see
Interfaces, _ := net.Interfaces()
fmt.Println(interfaces) //[{1 65536 lo up|loopback} {2 1500 eth0 34:17:eb:be:f1:23 up|broadcast|multicast}] Type: MTU (Maximum Transmission Unit), Network Interface Name, support status
Hp := net.JoinHostPort("", "8080")
fmt.Println(hp) //, which forms an addr string representation based on ip and port
Lt, _ := net.LookupAddr("")
fmt.Println(lt) //[localhost], find a mapping list based on the address to change the address
Cname, _ := net.LookupCNAME("www.baidu.com")
fmt.Println(cname) //www.a.shifen.com, find the canonical dns host name
Host, _ := net.LookupHost("www.baidu.com")
fmt.Println(host) //[], find the host name of the given domain name
Ip, _ := net.LookupIP("www.baidu.com")
fmt.Println(ip) //[], find the ip address of the given domain name, you can find it by nslookup www.baidu.com.

Before explaining the following function usage, describe several noun meanings (refer to the following connection: http://blog.sina.com.cn/s/blog_7ff492150101kqbh.html):

Domain name resolution record A, CNAME, MX, NS, TXT, AAAA, SRV, explicit url, implicit URL meaning

1. A record (IP point): resolves the domain name (www.xxx.com) to a specified IP. Users can resolve the domain name to their own Web server, as well as set a level two domain name for that domain name.

2. CNAME record (Canonical name alias point): the equivalent of using a subdomain name instead of an IP address. (Pros: If the IP address changes, you only need to change the sub-domain name resolution.) )

3. MX record: Point to a mail server to locate the mail server based on the address suffix of the recipient when the e-mail system sends mail.

4. NS RECORD: 1. Resolves server records. Used to indicate which server resolves the domain name, where the NS record only takes effect on the subdomain. For example, if the user wishes to resolve coco.mydomain.com by the server, the NS records for coco.mydomain.com need to be set.


·“ The smaller the number in priority indicates the higher the level;

·“ IP address/hostname can either fill in the IP address or fill in a host address such as ns.mydomain.com, but must ensure that the host address is valid. For example, the NS records of the coco.mydomain.com point to the ns.mydomain.com, the NS record is set at the same time also need to set the point of the ns.mydomain.com, otherwise the NS record will not be parsed properly;

• Priority: NS records take precedence over a record. That is, if a host address has both an NS record and a record, the A record does not take effect. The NS record here only takes effect on the subdomain.

5. TXT record: Set up contact information for a host name or domain name, such as:

admin in TXT "admin, Phone: 13901234567"

Mail in TXT "email host, store in XXX, Manager: AAA"

Jim in TXT "contact:abc@mailserver.com"

That is, you can set up TXT in order to get someone to contact you.

6. AAAA record 1. (AAAA record): A DNS record used to resolve a domain name to an IPv6 address. Users can resolve a domain name to an IPv6 address, or they can resolve a subdomain to a IPV6 address. (Set AAAA record:

I. Fill in the domain name of the host record. If you add a pan-resolution, fill in *. If the primary domain is parsed directly, leave it blank or fill in @.

II. The record type is AAAA. The record value is an IP address and can only be filled in with an IPv6 address (e.g.: 1).

III. MX priority does not need to be filled in.

Iv. the system is automatically generated when the TTL is added, and the default is 600 seconds. )

7. SRV record: is typically applied to Microsoft's Active Directory when it is set. DNS can be independent of Active Directory, but Active Directory must have DNS Help to work. In order for the Active Directory to work properly, the DNS server must support service location (SRV) resource records, which map the service name to the server name that provides the service. Active Directory clients and domain controllers use SRV resource records to determine the IP address of the domain controller.

This technical details please refer to the corresponding website (see forum post http://bbs.28tui.com/forum.php?mod=viewthread&tid=2321129)

8. Explicit URL record: When the domain name is accessed, it automatically jumps to the other network address (URL) that is referred to, at which point the address of the jump is displayed in the browser address bar.

9. Stealth URL Record: When the domain name is accessed, it automatically jumps to the other network address (URL) that is referred to, and the original domain address is displayed in the browser address bar.

Func lookupmx (name string) (MX []*mx, err Error)  //finds DNS MX mail exchange records for the specified domain name and returns in order of precedence.
Func Lookupns (name string) (ns []*ns, err Error)    //Returns the DNS NS record for the specified domain name
func lookupport (Network, Service string) (port int, err Error)           // Returns the port for the specified network and service
Func lookupsrv (service, proto, name string) (CNAME string, Addrs []*srv, err Error)     //SRV query for the specified service service, the Protocol protocol, and the name Domain name, where the proto protocol represents TCP or UDP, and the returned record records are sorted by priority. The same priority is randomly ordered according to weight weights. The LOOKUPSRV function constructs DNS for queries according to the RFC 2782 standard. In other words, it queries _service._proto.name. When both the service and proto parameters are empty strings, Lookupsrv will look for name directly.
Func lookuptxt (name string) (txt []string, err Error)  //Find DNS TXT record for the specified domain name
func splithostport (Hostport string ) (host, port string, err Error)  //splithostport The following form of network address into the form host and port, where the pre-split format is as follows: "Host:port", "[host]:p ort" or "[Ipv6-host%zone]:p ort" where the address or hostname of IPv6 must be enclosed in square brackets, such as "[:: 1]:80", "[Ipv6-host]:http", "[ipv6-host%zone]:80"

Next, tell the error that exists in the net package:

Type error//indicates a network error

Type Error interface {
Error //error
Timeout() bool // Is the error a timeout? Is the error a timeout error?
Temporary() bool // Is the error temporary? Is this a temporary error?
Any struct that implements the method in the error interface implements the network error

It mainly has the following centralized errors:

Type addrerror//network address error

Type AddrError struct {
Err string //Error
Addr string //address string representation
Func (e *addrerror) error () string//Error
Func (e *addrerror) temporary () bool//Whether the error is a temporary error 

Func (e *addrerror) timeout () bool//Whether the error is a time-out error

Type dnsconfigerror//DNS configuration error, indicating error during read machine DNS configuration

type DNSConfigError struct {
	Err error
Func (e *dnsconfigerror) Error () string
Func (e *dnsconfigerror) temporary () bool
Func (e *dnsconfigerror) Timeout () bool

Type Dnserror//dns error, indicating DNS query error

Type DNSError struct {
Err string // description of the error, error description
Name string // name looked for, query name
Server string // server used, service
IsTimeout bool, whether it times out
Func (e *dnserror) Error () string
Func (e *dnserror) temporary () bool
Func (e *dnserror) Timeout () bool

Take Dnserror as an example to illustrate the use of net care error

package main

import (

func main() {
	dnserror := net.DNSError{
		Err:       "dns error",
		Name:      "dnserr",
		Server:    "dns search",
		IsTimeout: true,
	fmt.Println(dnserror.Error())     //lookup dnserr on dns search: dns error
	fmt.Println(dnserror.Temporary()) //true
	fmt.Println(dnserror.Timeout())   //true
	fmt.Println(dnserror.Server)      //dns search
	fmt.Println(dnserror.Err)         //dns error
	fmt.Println(dnserror.Name)        //dnserr
	fmt.Println(dnserror.IsTimeout)   //true
Type invalidaddrerror//Invalid address error 
Type Invalidaddrerror string

Func (e invalidaddrerror) Error () string
Func (e Invalidaddrerror) temporary () bool
Func (e invalidaddrerror) Timeout () bool 

Type operror//Operation error, Operror is a function that often backs a knife in the net package, which describes an incorrect operation, network type, and address.

Type OpError struct {

Op string //Op is the operation that caused the error, such as "read" or "write"

Net string //Net indicates the type of network where the error occurred, such as tcp or udp6

Addr Addr //Addr indicates a network boycott with an error

Err error //Err indicates an error

Func (e *operror) Error () string
Func (e *operror) temporary () bool
Func (e *operror) Timeout () bool

Most of the errors in the Operror error include the following error:

var (
    ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")

Type parseerror//Parse error, ParseError represents a malformed string, where type represents the desired format.

type ParseError struct {
	Type string
	Text string
Func (e *parseerror) error () string//error expressed as a string

Type unknownnetworkerror//unknown network error

Type Unknownnetworkerror string

Func (e unknownnetworkerror) Error () string
Func (e Unknownnetworkerror) temporary () bool
Func (e unknownnetworkerror) Timeout () bool

Type ADDR//network terminal address

Type Addr interface {
Network() string // network name
String() string // address string representation

Type Conn//conn is a generic stream-oriented network connection, and multiple Goroutine can call methods in Conn at the same time.

Type Conn interface {
// Read reads data from the connection. The Read method returns an error indicating a timeout after a certain fixed time limit. The TImeout()==True of the error
Read(b []byte) (n int, err error)
// Write writes data to conn. Similar to Read, the Write method will return a timeout error after a certain fixed time. The error Timeout()==True
Write(b []byte) (n int, err error)
// The Close method closes the connection, and any blocked Read or Write methods will no longer block and return an error.
Close() error
// return local network address
LocalAddr() Addr
// return the remote network address
RemoteAddr() Addr
/ / Set the connection read and write deadline, it is equivalent to call SetReadDeadline and SetWriteDeadline for conn connection read and write deadline settings. Where the deadline is an absolute time,
        //After the deadline time, any read and write operations are no longer blocked, but directly fail. Deadline works for all subsequent I/O operations, not just the next read or write operation.
// : One: Idle timeout, this method implements two types of timeouts. It is special to extend the timeout period after each successful read or write operation. When there is no read/write operation idle, it will time out; Second: the parameter t is Zero value means no setting
        / / timeout period, that is, no timeout timeout
SetDeadline(t time.Time) error
/ / Set the read operation deadline, the parameter t is zero value means no deadline
SetReadDeadline(t time.Time) error
// Set the write operation of the connection, the parameter t is zero, indicating that the deadline is not set.
// Even if the write timeout occurs, it is possible that the number of write words n>0 indicates that some data was successfully written, but the data is not written.
SetWriteDeadline(t time.Time) error

The Func Dial (network, address string) (Conn, error)//dial is connected to the network that specifies address and name, where the net contains the following: "TCP", "TCP4" (ipv4-only), "Tcp6" (ipv6-only), "UDP", "UDP4" (ipv4-only), "Udp6" (ipv6-only), "IP", "IP4" (ipv4-only), "IP6" (ipv6-only), "Unix", "Uni Xgram "and" Unixpacket ". For TCP and UDP networks, the addresses form is as follows Host:port, which is exercised in accordance with Joinhostport and addresses form in Splithostport functions. An example is shown below:

Dial("tcp", "")
Dial("tcp", "google.com:http")
Dial("tcp", "[2001:db8::1]:http")
Dial("tcp", "[fe80::1%lo0]:80")
For IP networks, the network must be Ip,ipv4 or IPv6, and they must be followed by a colon and protocol number protocol name, and this address must be an IP address, for example:
Dial("ip4:1", "")
Dial("ip6:ospf", "::1")
For UNIX networks, address must be the path to a file system.

Func dialtimeout (Network, address string, timeout time. Duration) (Conn, error)//This function is similar to the dial function, but one more time-out setting timeout, which contains the domain name resolution if required
Func fileconn (f *os. File) (c Conn, err Error)//fileconn Returns a copy of the network connection to file F, and when the call is complete, the user needs to close the file F itself, because it is a copy relationship, so closing C and closing F do not affect each other.
The Func Pipe (Conn, Conn)//pipe creates a synchronous full-duplex network connection in memory. The Conn interface is implemented on both ends of the connection. One end of the read corresponds to the other end of the write, in which the copied data is copied directly between the two ends, without the internal cache.

Type Dialer//contains an option to connect to an address,//The value of 0 for each parameter in the Dialer struct corresponds to the absence of that value, so the dial function in the Dialer that calls the 0 value is equivalent to calling the dial function directly

Type Dialer struct {
// Timeout is the maximum length of time that the dial operation waits for the connection to be established. The default value means there is no timeout. If the Deadline field is also set, the dial operation may fail earlier.
// The operating system may enforce its timeout setting regardless of the timeout. For example, TCP (system) timeouts are typically around 3 minutes. Timeout is a relative time, a time period, and Deadline is a must
        //For time, it is time, this is the difference between the two
Timeout time.Duration

       // Deadline is a specific time point period after which the dial operation will fail. If the Timeout field is also set, the dial operation may fail earlier. A value of zero means there is no deadline.
Deadline time.Time

       // LocalAddr is the local address used when dialing an address.
// The address must be of a type compatible with the dial network.
// If nil, a local address will be automatically selected.
LocalAddr Addr

        // When the network type is tcp and a host name has multiple dns record addresses, DualStack allows a dial to create multiple ipv4 and ipv6 connections and returns the first created connection.
DualStack bool

        // KeepAlive specifies the time period for which a network connection is kept declared; if it is 0, keep-alive is disabled. This value is ignored when the network protocol does not support keep-alives.
// This field is ignored for network connections that do not support keep-alive.
KeepAlive time.Duration
Func (d *dialer) Dial (network, address string) (Conn, error)//dial connection to the specified address on the specified network. For detailed usage See dial function for description of network and address parameters

Type Flags

Type Flags UINT

Const (
FlagUp Flags = 1 << iota // The interface is in an interactive state
FlagBroadcast // Interface supports broadcast
FlagLoopback // The interface is a loopback interface
FlagPointToPoint // The interface is point-to-point
FlagMulticast // Interface supports multicast
Func (f Flags) string () string//F is represented by a string

Type HARDWAREADDR//hardware address, HARDWAREADDR represents a physical hardware address

Type hardwareaddr []byte
Func Parsemac (S string) (HW hardwareaddr, err Error)//parses a string into a hardware physical address where the PARSEMAC function parses an IEEE 802 MAC-48, using the following format EUI-48 or EUI-64 hardware address: 

A string representation of the Func (a hardwareaddr) string () string//Hardware address

The type Interface//interface represents a mapping between the network interface name and the index, and he also contains network pretext device information.

Type Interface struct {
Index int // index, must be a positive integer
MTU int // maximum transmission unit
Name string // Name, for example: "en0", "lo0", "eth0.100"
HardwareAddr HardwareAddr //hardware address, for example: IEEE MAC-48, EUI-48 and EUI-64 form
Flags Flags // flags, for example: FlagUp, FlagLoopback, FlagMulticast
Func interfacebyindex (index int) (*interface, error)//returns the appropriate interface via the index specified
Func interfacebyname (name string) (*interface, error)//returns the appropriate interface by the name specified
Func (Ifi *interface) Addrs () ([]ADDR, error)//return address of the specified interface
Func (Ifi *interface) Multicastaddrs ([]addr, error)//multicastaddrs returns the multicast group address to which the network interface Ifi joined.

The type Listener//listener is a common network listener interface for stream-oriented network protocols. Multiple threads may call a listener method at the same time. 
Type Listener interface {

Accept() (c Conn, err error) // waits and returns the next connection to the connection

Close() error //Close the listener. After closing, any operations that block the accept are no longer blocked and return error.

Addr() Addr //Returns the network address of the interface
Func Filelistener (f *os. File) (l Listener, err Error)//Returns the replication of network Listener for file F.
Func Listen (NET, laddr string) (Listener, error)//returns the Listener that is listening on a local network address laddr. The network type parameter net must be a stream-oriented network: "TCP", "TCP4", "TCP6", "Unix", or "Unixpacket". See the dial function for LADDR syntax.

Type Packetconn
Func filepacketconn (f *os. File) (c packetconn, err Error)
Func listenpacket (NET, laddr string) (Packetconn, error)

The Type MX//mx represents a DNS MX record (mail exchange record) that locates the mail server based on the recipient's address suffix.

type MX struct {
	Host string
	Pref uint16
The type NS//NS represents a DNS NS record (a domain name server record) that specifies which DNS server the domain name is to parse. 
type NS struct {
	Host string

The type SRV//srv represents a DNS SRV record (resource record) that records which computer is provided by a service. 
type SRV struct {
	Target   string
	Port     uint16
	Priority uint16
	Weight   uint16



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.