Go Network Programming Notes

Source: Internet
Author: User

This article is to learn <<go language programming >>--Tsinghua University Press (Wang Peng authored) January 2014 first edition of some notes, if there is infringement, please inform the author, will be deleted within 24 hours, reproduced please indicate the source!

1. NET packages are available in the standard library to support network communication based on network layer (IP), Transport Layer (TCP/UDP), and application layer (such as HTTP,FTP,SMTP).

2. IP address and Domain name resolution

-IP Address Type: Type ip[] byte

-Common functions

- func Parseip (s string) IP verifies the legality of IP, returning an IP address object or nil.

- func (IP IP) string () string converts IPv4 into dotted decimal format strings, IPV6 converted to colon-delimited shorthand strings.

 Package Main Import (    "FMT"    "NET") Func main () {    addr:= "192.168.0.1"    IP:= net. Parseip (addr)    if ip = = Nil {        FMT. Println ("IP invalid!" )    Else  {        fmt. PRINTLN ("IP is:", IP.) String ())    }}
View Code

-IPMask Address Type: Type IPMask [] byte (only IPv4 has default subnet mask)

-Common functions

- func ipv4mask (a,b,c,d byte) IPMask generates a subnet mask address from a 32-bit IPV4 address and returns.

- func (IP IP) defaultmask () IPMask returns the default subnet mask for IPV4, otherwise returns nil

- func (M IPMask) Size (ones,bits int) returns the number of mask bits (ones) and the total mask length (bits) through the subnet mask object. If it is a non-standard subnet mask, 0,0 is returned.

- func (IP IP) mask (mask ipmask) IP Returns the result of the IP address and subnet mask, which is the network address.

 package   main  import   ( fmt "" Net " = net. Parseip ("192.168.0.1" )  if  IP == nil {FMT. Println ( "Invalid ip!" )} Mask:  = IP. Defaultmask () fmt. Println ( Subnet mask is: " =  IP. Mask (mask) fmt. Println ( Network address is: ", Network) ones, bits:  = mask. Size () fmt. Println ( "Mask ones:", ones, "Total Mask Len is:"  
View Code

-IPADDR Structure Type

-Definition: type ipaddr struct {IP IP} , many functions and methods will return a pointer to the struct body.

-IPAddr primary role is used for domain name resolution service (DNS)

-Common functions

- func resolveipaddr (NET, addr string) (*ipaddr,error) net represents the network type (IP,IP4,IP6), addr is an IP address, or a domain name.

-Domain Name resolution

 Package Main Import (    "FMT"    "NET" "    OS") Func main () {    addr:= "www.baidu.com"    IP, err:= Net. RESOLVEIPADDR ("IP", addr)    if err ! = nil {        FMT. Println ("Resolvation error:#", err. Error ())        OS. Exit (1)    }    fmt. Println ("Resolved address is:", IP. String ())}
View Code

3. Host information Query

-most hosts in the network have multiple IP addresses, so it is not good to use the host name to get the IP address of a host. A host may also have aliases.

-Common functions

- func lookuphost (host string) (Addrs []string, err Error) returns the host address list or error.

 Package Main Import (    "FMT"    "NET") Func main () {    name:= "www.baidu.com"    Addrs, err:=  Net. Lookuphost (name)    if err ! = nil {        FMT. Println ("Lookuphost error:#", err. Error ())    Else  {        for _, s: = range Addrs {            fmt. Println (s)        }     }}
View Code

- func lookupcname (name string) (CNAME string, err Error) queries the host official name.

4. Service Information Enquiry

-Query SRV records

-Service Port Query

 

5. Go Network Programming

-Traditional socket programming

-Flow Socket Step:

-The server and the client call the socket () to create the socket separately

-The server and the client call the bind () function to bind the server address separately

-The server calls Liste () listener, the client calls connect () to connect and makes a connection request to the server.

-The server calls accept () accepts the request and re-creates a socket for the communication connection with the client.

-Call Send () and recv () to send and receive data.

-either side can call Close () off

-Datagram sockets do not require listening and connection steps, and the server and client can send and receive data from each other as long as the socket is established.

-Network programming in go.

-Encapsulation of traditional socket programming. No matter what form of connection you want to use, func Dial (net,addr string) (Conn,error) Net is the protocol name (such as Tcp,ip), addr is the IP address or domain name, plus: port number. such as: conn, err: = Net. Dial ("TCP", "192.168.0.1:5000") conn, err: = Net. Dial ("ip4:icmp", "www.baidu.com")

-Dail () supports the following protocols: TCP,TCP4,TCP6, UDP,UDP4,UDP6,IP,IP4,IP6

-The data can be sent and received after the connection is successfully established.

6.TCP

-TCP works in the transport layer, facing the connection, TCP program design belongs to the C/S mode.

type tcpaddr struct{    IP ip    int}

- func resolvetcpaddr (net,addr string) (*tcpaddr,error) translates the network address into a TCPADDR address structure. www.google.com:80

-Net: Network protocol name, can be TCP,TCP4,TCP6

-Addr:ip address or domain name, if IPv6 must be surrounded by "[]", the port number is ":p ort" in the form of the back

-Common methods:

- func (A * tcpaddr) net () string returns the network protocol name of the Tcpaddr address object, such as "TCP"

- func (A * tcpaddr) string () string converts the tcpaddr into a string form.

 Package Main Import (    "FMT"    "NET") Func main () {    networktype:= "TCP4"    addr:= "www.baidu.com : "    tcpaddr, err:= net." Resolvetcpaddr (Networktype, addr)    if err ! = nil {        FMT. Println ("resolvetcpaddr error:", err.) Error ())    Else  {        fmt. Println ("The Network Type is:", Tcpaddr.network (), "IP is:", Tcpaddr.string ())    }}
View Code

-Tcpconn Object

-The communication between the client and the server in TCP programming is connected through the Tcpconn object.

-Tcpconn is the implementation of the Conn interface, which binds the server's network protocol and address information.

type Tcpconn struct{    //  defined as empty structure }

-Through the Tcpconn connection object, you can implement full-duplex communication between the client and the server. You can send and receive data via Tcpconn's Read ()/write (), both of which cause blocking.

- func (c * tcpconn) Read (b []byte) (n int, err error)

- func (c * tcpconn) Write (b []byte) (n int, err error)

-TCP Server

-TCP server registers a common port number before calling Listentcp () to create a TcpListener listener on this port and listen for connection requests.

-Enables the Accept () receive request for the TcpListener object, returning a protocol-related Conn object (this is the Tcpconn object)

-If a new Tcpconn object is returned, the server can send and receive data as if it were called by the Read ()/write () method of the object.

type TcpListener struct{    //  contains filtered or unexported fields.  * tcpaddr) (*tcplistener, error)
-NET:TCP/TCP4/TCP6
-Laddr:local Server address

- func (L * tcplistener) Accept () (c conn,err error) returns Tcpconn (implements the Conn interface) object.

-If you want to get a correspondence address during communication

- func (c * tcpconn) localaddr/remoteaddr () Addr

 PackageMainImport (    "FMT" "NET" "OS") func checkerror (err error) {ifErr! =Nil {fmt. fprintf (OS. Stderr,"Fatal Error:%s", Err. Error ()) OS. Exit (1)}}func Main () {tcpaddr, err:= Net. RESOLVETCPADDR ("TCP", ": 5000") checkerror (err) TcpListener, err:= Net. LISTENTCP ("TCP", TCPADDR) checkerror (err) for{tcpconn, err:=tcplistener.accept ()ifErr! =Nil {Continue} handleclient (Tcpconn) tcpconn.close ()}}func handleclient (conn net. Conn) {var buf [512]byte     for{n, err:= Conn. Read (buf[0:]) ifErr! =Nil {return} raddr:=Conn. Remoteaddr () fmt. Println ("Receive from client:", raddr.string (), "#", String (buf[0: N]) _, Err= Conn. Write ([]byte("Welcome client!"))        ifErr! =Nil {return        }    }}
View Code

-Concurrent Server

 PackageMainImport (    "FMT" "NET" "OS") func checkerror (err error) {ifErr! =Nil {fmt. fprintf (OS. Stderr,"Fatal Error:%s", Err. Error ()) OS. Exit (1)}}func Main () {tcpaddr, err:= Net. RESOLVETCPADDR ("TCP", ": 5000") checkerror (err) TcpListener, err:= Net. LISTENTCP ("TCP", TCPADDR) checkerror (err) for{tcpconn, err:=tcplistener.accept ()ifErr! =Nil {Continue} go handleclient (tcpconn)}}func handleclient (conn net. Conn) {defer Conn. Close () var buf [512]byte     for{n, err:= Conn. Read (buf[0:]) ifErr! =Nil {return} raddr:=Conn. Remoteaddr () fmt. Println ("Receive from client:", raddr.string (), "#", String (buf[0: N]) _, Err= Conn. Write ([]byte("Welcome client!"))        ifErr! =Nil {return        }    }}
View Code

-TCP Client

-Work Flow

-After obtaining the server address and port number, call the DIALTCP () function to make a connection request to the server and return the Tcpconn object if the request succeeds

-Call the Read () and write () methods of the Tcpconn object to send and receive messages.

-Common methods:

- func dialtcp (net string, LADDR, Raddr * tcpaddr) (* tcpconn, error) NET:TCP/TCP4/TCP6

- func (c * tcpconn) Close () Error

 PackageMainImport (    "FMT" "NET" "OS") func checkerror (err error) {ifErr! =Nil {fmt. fprintf (OS. Stderr,"Fatal Error:%s", Err. Error ()) OS. Exit (1)}}func Main () {var buf [512]bytetcpaddr, err:= Net. RESOLVETCPADDR ("TCP", "127.0.0.1:5000") CheckError (ERR) conn, err:= Net. DIALTCP ("TCP", Nil, tcpaddr) checkerror (err) raddr:=Conn. Remoteaddr () N, err:= Conn. Write ([]byte("Hello server!") ) CheckError (ERR) n, err= Conn. Read (buf[0:]) CheckError (Err) fmt. Println ("Reply from server:", raddr.string (), "#", String (buf[0: n])) Conn. Close ()}
View Code

7. UDP

-UDPADDR Address structure

type udpaddr struct{    IP ip    int}

-Corresponds to TCP, UDP has Resolveudpaddr (), Network (), and string (); Prototypes and functions are the same.

-Udpconn Object

-UDP in C/S through Udpconn object connection, Udpconn is the implementation of Conn interface, binding the server's network protocol and address.

- type udpconn struct {//empty}

-UDP does not guarantee the reliability and order of the communication.

-The Udpconn object provides a way to handle UDP data to ensure reliable

- func (c * udpconn) readfromudp (b []byte) (n int, addr * udpaddr, err Error)

- func (c * udpconn) writetoudp (b []byte, addr * udpaddr) (int, error)

-UDP Server

-Work Flow

-The server registers a port number before calling LISTENUDP () to wear a Udpconn connection object on this port, and the resume is unreliable on that object and client.

-If the server and a client establish a udpconn connection, you can use the READFROMUDP () and WRITETOUDP () methods of the object.

-the UDP server will still accept the next connection request, regardless of whether the last communication was completed or normal.

-Common methods.

- func listenudp (NET string, Laddr * udpaddr) (* udpaddr, error)

Go Network Programming Notes

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.