go net 包详解1

eclipser1987 · · 8437 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

/**
 * 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]))

}



有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:eclipser1987

查看原文:go net 包详解1

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

8437 次点击  ∙  1 赞  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传