go net 包详解

转载 2017年09月21日 18:15:37
/**
 * Created by Administrator on 13-12-9.
 */
package main

import (
    "fmt"
    "os"
    "net"
)

/**
 * 将string类型的ip地址转换为IP对象
 */
func main() {

    name := "192.168.1.97"

    ip := net.ParseIP(name)

    if ip == nil {
        fmt.Fprintf(os.Stderr, "Err:无效的地址")
        return
    }

    fmt.Fprintf(os.Stdout, "IP: %s %s\n", ip, ip.String())
    defaultMask := ip.DefaultMask()
    fmt.Fprintf(os.Stdout, "DefaultMask: %s %s\n", defaultMask, defaultMask.String())

    ones, bits := defaultMask.Size()
    fmt.Fprintf(os.Stdout, "ones: %d bits: %d\n", ones, bits)
}
/**
 * Created by Administrator on 13-12-9.
 */
package main

import (
    "net"
    "fmt"
    "os"
)

/**
 * 根据IP和掩码获得网络
 */
func main() {
    name := "192.168.1.97"

    ip := net.ParseIP(name)

    mask := ip.DefaultMask()

    network := ip.Mask(mask)

    fmt.Fprintf(os.Stdout, "network: %s", network.String()) // 192.168.1.0

    // ip:      192.168.1.97
    // mask:    255.255.255.0
    // network: 192.168.1.0
}
/**
 * Created by Administrator on 13-12-9.
 */
package main

import (
    "net"
    "fmt"
    "os"
)

/**
 * 将域名解析Ip地址
 * 获得域名对应的所有Ip地址
 */
func main() {

    domain := "www.baidu.com"
    ipAddr, err := net.ResolveIPAddr("ip", domain)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Err: %s", err.Error())
        return
    }
    fmt.Fprintf(os.Stdout, "%s IP: %s Network: %s Zone: %s\n", ipAddr.String(), ipAddr.IP, ipAddr.Network(), ipAddr.Zone)

    // 百度,虽然只有一个域名,但实际上,他对应电信,网通,联通等又有多个IP地址
    ns, err := net.LookupHost(domain)
    if err != nil {
        fmt.Fprintf(os.Stderr, "Err: %s", err.Error())
        return
    }

    for _, n := range ns {
        fmt.Fprintf(os.Stdout, "%s", n) // 115.239.210.26    115.239.210.27 这2个地址打开都是百度
    }
}
/**
 * Created by Administrator on 13-12-9.
 */
package main

import (
    "net"
    "fmt"
    "os"
)

/**
 * 查看主机服务器(service)占用的端口,这些服务,都是tcp或者udp的
 */
func main() {

    port, err := net.LookupPort("tcp", "telnet") // 查看telnet服务器使用的端口

    if err != nil {
        fmt.Fprintf(os.Stderr, "未找到指定服务")
        return
    }

    fmt.Fprintf(os.Stdout, "telnet port: %d", port)

}
/**
 * Created by Administrator on 13-12-9.
 */
package main

import (
    "net"
    "fmt"
    "os"
)

func main() {

    // TCPAddr 包涵IP 和 Port

    // 将一个host地址转换为TCPAddr。host=ip:port
    pTCPAddr, err := net.ResolveTCPAddr("tcp", "www.baidu.com:80")
    if err != nil {
        fmt.Fprintf(os.Stderr, "Err: %s", err.Error())
        return
    }

    fmt.Fprintf(os.Stdout, "www.baidu.com:80 IP: %s PORT: %d", pTCPAddr.IP.String(), pTCPAddr.Port)
}
/**
 * Created by Administrator on 13-12-10.
 */
package main

import (
    "net"
    "fmt"
    "os"
    "io/ioutil"
)

func main() {

    url := "www.baidu.com:80"

    pRemoteTCPAddr, err := net.ResolveTCPAddr("tcp4", url)

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
        return
    }

    // pLocalTCPAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:7070")

    pTCPConn, err := net.DialTCP("tcp", nil/*pLocalTCPAddr*/, pRemoteTCPAddr)

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
        return
    }


    n, err := pTCPConn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
        return
    }
    defer pTCPConn.Close()

    fmt.Fprintf(os.Stdout, "writed: %d\n", n)

    buf, err := ioutil.ReadAll(pTCPConn)
    r := len(buf)
    fmt.Fprintf(os.Stdout, string(buf[:r]))
    fmt.Fprintf(os.Stdout, "readed: %d\n", r)

}
/**
 * Created by Administrator on 13-12-10.
 */
package main

import (
    "net"
    "fmt"
    "os"
    "time"
)

func main() {

    pTCPAddr, error := net.ResolveTCPAddr("tcp4", ":7070")
    if error != nil {
        fmt.Fprintf(os.Stdout, "Error: %s", error.Error())
        return
    }
    pTCPListener, error := net.ListenTCP("tcp4", pTCPAddr)
    if error != nil {
        fmt.Fprintf(os.Stdout, "Error: %s", error.Error())
        return
    }
    defer pTCPListener.Close()

    for {
        pTCPConn, error := pTCPListener.AcceptTCP()
        if error != nil {
            fmt.Fprintf(os.Stdout, "Error: %s", error.Error())
            continue
        }
        go connHandler(pTCPConn)
    }
}

func connHandler(conn *net.TCPConn) {
    defer conn.Close()
    now := time.Now()
    conn.Write([]byte(now.String() + "\n"))
}
/**
 * Created by Administrator on 13-12-10.
 */
package main

import (
    "net"
    "fmt"
    "os"
    "time"
)

func main() {

    //url := "baidu.com:80"
    url := "facebook.com:80"
    conn, error := net.DialTimeout("tcp", url, time.Second * 10) // 带有超时限制的conn
    if error != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", error.Error())
        return
    }

    n , error := conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
    if error != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", error.Error())
        return
    }

    fmt.Fprintf(os.Stdout, "writed: %d", n)

    buf := make([]byte, 2048)
    n, error = conn.Read(buf)
    if error != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", error.Error())
        return
    }

    fmt.Fprintf(os.Stdout, string(buf[:n]))
}
/**
 * Created by Administrator on 13-12-10.
 */
package main

import (
    "net"
    "fmt"
    "os"
)

/**
 * UDP 服务器
 */
func main() {
    pUDPAddr, err := net.ResolveUDPAddr("udp", ":7070")

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
        return
    }

    pUDPConn, err := net.ListenUDP("udp", pUDPAddr)

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
        return
    }

    defer pUDPConn.Close()

    for {

        buf := make([]byte, 256)
        n , pUDPAddr, err := pUDPConn.ReadFromUDP(buf)

        if err != nil {
            fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
            return
        }
        fmt.Fprintf(os.Stdout, "readed: %d", n)

        n, err = pUDPConn.WriteToUDP(buf, pUDPAddr)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
            return
        }
        fmt.Fprintf(os.Stdout, "writed: %d", n)
    }
}
/**
 * Created by Administrator on 13-12-10.
 */
package main

import (
    "net"
    "fmt"
    "os"
)

/**
 * UDP 客户端
 */
func main() {

    pUDPAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:7070")

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error ResolveUDPAddr: %s", err.Error())
        return
    }

    pUDPConn, err := net.DialUDP("udp", nil, pUDPAddr)

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error DialUDP: %s", err.Error())
        return
    }

    n, err := pUDPConn.Write([]byte("你好啊!!!"))

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error WriteToUDP: %s", err.Error())
        return
    }

    fmt.Fprintf(os.Stdout, "writed: %d", n)

    buf := make([]byte, 1024)
    n, _, err = pUDPConn.ReadFromUDP(buf)

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error ReadFromUDP: %s", err.Error())
        return
    }

    fmt.Fprintf(os.Stdout, "readed: %d  %s", n, string(buf[:n]))
}
/**
 * Created by Administrator on 13-12-10.
 */
package main

import (
    "net"
    "fmt"
    "os"
)

/*
很多时候,服务器会处理多个端口的监听!可以使用select轮询处理这种情况

 */
func main() {

    lsr, err := net.Listen("tcp", ":7070")

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
        return
    }

    for {
        conn , err := lsr.Accept()
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
            continue
        }

        go connHandler(conn)

    }

    fmt.Println("Done !")
}

func connHandler(conn net.Conn) {
    defer conn.Close()

    var buf[512]byte
    for {
        n , err := conn.Read(buf[0:])
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
            return
        }
        _, err = conn.Write(buf[0:n])
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
            return
        }
    }
}
/**
 * Created by Administrator on 13-12-10.
 */
package main

import (
    "net"
    "fmt"
    "os"
    "bufio"
)

func main() {

    conn, err := net.Dial("tcp", "192.168.1.97:7070")
    if err != nil {
        fmt.Sprint(os.Stderr, "Error: %s", err.Error())
        return
    }


    go func() {
        var buf [512]byte
        for {
            n , err := conn.Read(buf[0:])
            if err != nil {
                fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
                return
            }
            fmt.Fprintf(os.Stdout, string(buf[0:n]))
        }

    }()

    for {
        fmt.Fprintf(os.Stdout, "\n输入:")
        pReader := bufio.NewReader(os.Stdin)
        line, _, err := pReader.ReadLine()
        if err != nil {
            fmt.Fprintf(os.Stderr, "Error: %s", err.Error())
            return
        }
        conn.Write(line[0:])
    }
}
/**
 * Created by Administrator on 13-12-10.
 */
package main

import (
    "net"
    "fmt"
    "os"
)

/**
 UDP Server
 */
func main() {

    packetConn, err := net.ListenPacket("udp", ":7070")

    if err != nil {
        fmt.Fprintf(os.Stdout, "Error: %s", err.Error())
        return
    }
    defer packetConn.Close()

    var buf [512]byte
    for {
        n , addr, err := packetConn.ReadFrom(buf[0:])
        if err != nil {
            fmt.Fprintf(os.Stdout, "Error: %s", err.Error())
            return
        }

        fmt.Fprintf(os.Stdout, "recv: %s", string(buf[0:n]))

        _, err = packetConn.WriteTo(buf[0:n], addr)
        if err != nil {
            fmt.Fprintf(os.Stdout, "Error: %s", err.Error())
            return
        }
    }


}
/**
 * Created by Administrator on 13-12-10.
 */
package main

import (
    "net"
    "fmt"
    "os"
    "time"
)

/**
 UDP Client
 */
func main() {
    conn, err := net.Dial("udp", "127.0.0.1:7070")

    if err != nil {
        fmt.Fprintf(os.Stdout, "Error: %s", err.Error())
        return
    }

    defer conn.Close()


    _, err = conn.Write([]byte("你好啊UDP"))
    if err != nil {
        fmt.Fprintf(os.Stdout, "Error: %s", err.Error())
        return
    }

    var buf [512]byte
    conn.SetReadDeadline(time.Now().Add(time.Second * 1))  // 阻塞,直到接收到消息,设置阻塞时间1秒
    n, err := conn.Read(buf[0:])
    if err != nil {
        fmt.Fprintf(os.Stdout, "Error: %s", err.Error())
        return
    }

    fmt.Fprintf(os.Stdout, "recv: %s", string(buf[0:n]))

}

转自:
http://blog.csdn.net/eclipser1987/article/details/17247519?hmsr=studygolang.com&utm_medium=studygolang.com&utm_source=studygolang.com

相关文章推荐

Go语言linux下构造tcp数据包(不使用net包和Cgo)

Golang可以通过syscall包中的相关socket函数(Windows和Linux中syscall中网络编程的函数不太一样)来进行网络编 程,可以用我们熟悉的方法使用raw socket,因为最...

Go net包介绍

与大多数语言一样,Go的标准库很全,因为Go的出现本来就是为了网络通信的高并发实现,所以其相关的网络库封装得更简洁,更Readable。这里来大致介绍几个网络库,掌握了学习方法,那么只要里面有那个库,...

Go网络编程之net/http包执行流程源码分析

1. http包建立web服务器 package main import (     "fmt"     "log"  ...
  • huwh_
  • huwh_
  • 2017-07-30 15:11
  • 187

Go利用net/http包搭建Web服务器

简介 利用Go的标准包net/http可以很方便的搭建服务器。实际上只需要一个函数和一个接口: net/http−−−−−−−\underline{net/http} package http ...

七、GO语言库学习--net/url包--go语言笔记

QueryEscape(s string) stringescape 转义string 到url queryQueryUnescape(s string) (string,err)转化 %AB 为 b...

Go语言学习之net/http包(The way to go)

生命不止,继续go go go!!!从包名就能看到了吧,是golang中提供http的包: provides HTTP client and server implementations.先看一个...

Go语言学习之net包(The way to go)

生命不止,继续go go go!!!不要问我net包和net/http包的区别,我们先会用,两者的区别慢慢去体会。net包有什么作用?Package net provides a portable i...

Go语言学习之net/url包(url相关操作)(the way to go)

生命不止,继续 go go go !!!今天跟大家分享的是是net/url package,从名字已经可以看出来了,与url相关的标准库。作用: Package url parses URLs an...

Go语言net/http 解读.

Http包提供实现HTTP客户端和服务端的方法与函数。 Get、Head、Post、PostForm配合使用实现HTTP请求: resp, err := http.Get("http://exam...

go程序包源码解读——golang.org/x/net/context

强烈建议读者先完成http://blog.golang.org/pipelines的阅读,此文对于go的channel的用法会让初学者有一种豁然开朗的感觉。 简介context是一个在go中时常用到的...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)