This is a creation in Article, where the information may have evolved or changed.
Go can also be like normal socket programming: create socket-------listen ...
Of course, there are net packages available in go, but if you want to implement some of the lower-level operations, such as building your own packets, you can do this in a more primitive way for socket programming.
The code is as follows:
Package Mainimport (. "FMT" "StrConv" "Strings" "Syscall") func Makeword (Low, high uint8) UInt32 {var ret uint16 = uint16 (high) <& Lt;8 + uint16 (Low) return UInt32 (ret)}func inet_addr (ipaddr string) [4]byte {var (ips = strings. Split (IPAddr, ".") IP [4]uint64 ret [4]byte] for I: = 0; I < 4; i++ {Ip[i], _ = StrConv. Parseuint (Ips[i], ten, 8)} for I: = 0; I < 4; i++ {Ret[i] = byte (Ip[i])} return Ret}func main () {var (sock syscall. Handle addr Syscall. SockaddrInet4 wsadata Syscall. Wsadata err Error) If Err = Syscall. WSAStartup (Makeword (2, 2), &wsadata); Err! = Nil {Println ("Startup error") return} defer syscall. WSACleanup () if sock, err = Syscall. Socket (Syscall.af_inet, Syscall. Sock_stream, Syscall. IPPROTO_IP); Err! = Nil {Println ("Socket create Error") return} defer syscall. Closesocket (sock) addr. Addr = Inet_addr ("61.135.169.105") addr. Port = If Err = Syscall. Connect (sock, &ADDR); Err! = Nil {Println ("Connect error") return} var (data syscall. Wsabuf sendstr string = "Hello" sendbutes uint32 overlapped syscall. Overlapped) data. Len = UInt32 (len (SENDSTR)) data. Buf = Syscall. Stringbyteptr (SENDSTR)//If Syscall is used. SendTo or Syscall.write send failed for unknown reason, err = Syscall. WSASend (sock, &data, 1, &sendbutes, 0, &overlapped, nil) if err! = Nil {Println ("Send error")} else {Println ("Send Success")}}
Note: Syscall. SendTo and Syscall.write two functions tried to send the failure, and I do not know why, in the Windows environment, it appears that only the wsa**** series of functions to send packets, but proved that go can also be used for the underlying network programming without the help of CGO
If reproduced please specify the source: http://blog.csdn.net/gophers/article/details/18666287