参看下面代码 :
package main import( "fmt" "net" // "io" "reflect" ) func main(){ conn, err := net.Dial("tcp","www.baidu.com:80") if err != nil { fmt.Println("err dialing,err:",err) return } defer conn.Close() fmt.Println("访问的公网ip地址是:",conn.RemoteAddr().String()) fmt.Println("本地地址:",conn.LocalAddr().String()) fmt.Println("“conn.LocalAddr()”所对应的数据类型是:",reflect.TypeOf(conn.LocalAddr())) fmt.Println("“conn.RemoteAddr().String()”所对应的数据类型是:",reflect.TypeOf(conn.RemoteAddr().String())) msg := "GET / HTTP/1.1\r\n" msg += "Host:www.baidu.com\r\n" msg += "Connection:close\r\n" msg +="\r\n\r\n" _,err =conn.Write([]byte(msg)) if err != nil { fmt.Println("writing string failed,",err) return } buf := make([]byte,4096) for { count,err := conn.Read(buf) if err != nil { break } fmt.Println(string(buf[0:count])) } }
参考:https://www.cnblogs.com/yinzhengjie/p/7261584.html