Golang client绑定本地IP和端口

àì夳堔傛蜴生んèń 2022-05-21 20:48 276阅读 0赞

有时需要指定网络通信时本地使用的IP地址和端口号。

在Go语言中可通过定义 Dialer 中LocalAddr 成员实现。
Dialer结构定义如下:

  1. // A Dialer contains options for connecting to an address.
  2. //
  3. // The zero value for each field is equivalent to dialing
  4. // without that option. Dialing with the zero value of Dialer
  5. // is therefore equivalent to just calling the Dial function.
  6. type Dialer struct {
  7. ...
  8. // LocalAddr is the local address to use when dialing an
  9. // address. The address must be of a compatible type for the
  10. // network being dialed.
  11. // If nil, a local address is automatically chosen.
  12. LocalAddr Addr
  13. }

Addr是接口类型,其定义如下:

  1. // Addr represents a network end point address.
  2. //
  3. // The two methods Network and String conventionally return strings
  4. // that can be passed as the arguments to Dial, but the exact form
  5. // and meaning of the strings is up to the implementation.
  6. type Addr interface {
  7. Network() string // name of the network (for example, "tcp", "udp")
  8. String() string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80")
  9. }

目前实现Addr接口的类型并且被net 库支持的类型 包括:TCPAddr、UDPAddr、IPAddr。

下面通过代码演示如何指定client 使用的IP和端口号。

例子中使用TCPAddr 类型。

client

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "net"
  6. "os"
  7. "time"
  8. )
  9. func DialCustom(network, address string, timeout time.Duration, localIP []byte, localPort int)(net.Conn,error) {
  10. netAddr := &net.TCPAddr{Port:localPort}
  11. if len(localIP) != 0 {
  12. netAddr.IP = localIP
  13. }
  14. fmt.Println("netAddr:", netAddr)
  15. d := net.Dialer{Timeout: timeout, LocalAddr: netAddr}
  16. return d.Dial(network, address)
  17. }
  18. func main() {
  19. serverAddr := "172.20.22.160:8080"
  20. // 172.28.0.180
  21. //localIP := []byte{0xAC, 0x1C, 0, 0xB4} // 指定IP
  22. localIP := []byte{} // any IP,不指定IP
  23. localPort := 9001 // 指定端口
  24. conn, err := DialCustom("tcp", serverAddr, time.Second*10, localIP,localPort)
  25. if err != nil {
  26. fmt.Println("dial failed:", err)
  27. os.Exit(1)
  28. }
  29. defer conn.Close()
  30. buffer := make([]byte, 512)
  31. reader := bufio.NewReader(conn)
  32. n, err2 := reader.Read(buffer)
  33. if err2 != nil {
  34. fmt.Println("Read failed:", err2)
  35. return
  36. }
  37. fmt.Println("count:", n, "msg:", string(buffer))
  38. select{}
  39. }

server

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "log"
  6. )
  7. func main() {
  8. addr := "0.0.0.0:8080"
  9. tcpAddr, err := net.ResolveTCPAddr("tcp",addr)
  10. if err != nil {
  11. log.Fatalf("net.ResovleTCPAddr fail:%s", addr)
  12. }
  13. listener, err := net.ListenTCP("tcp", tcpAddr)
  14. if err != nil {
  15. log.Fatalf("listen %s fail: %s", addr, err)
  16. } else {
  17. log.Println("rpc listening", addr)
  18. }
  19. for {
  20. conn, err := listener.Accept()
  21. if err != nil {
  22. log.Println("listener.Accept error:", err)
  23. continue
  24. }
  25. go handleConnection(conn)
  26. }
  27. }
  28. func handleConnection(conn net.Conn) {
  29. //defer conn.Close()
  30. var buffer []byte = []byte("You are welcome. I'm server.")
  31. n, err := conn.Write(buffer)
  32. if err != nil {
  33. fmt.Println("Write error:", err)
  34. }
  35. fmt.Println("send:", n)
  36. fmt.Println("connetion end")
  37. }

测试

启动client,只指定端口

  1. $ ./client
  2. netAddr: :9001
  3. count: 28 msg: You are welcome. I'm server.

启动client,指定IP,Port

  1. $ ./client
  2. netAddr: 172.28.172.180:9001
  3. count: 28 msg: You are welcome. I'm server

server输出

  1. ./sever
  2. 2018/06/19 18:15:41 rpc listening 0.0.0.0:8080
  3. send: 28
  4. connetion end

查看连接

  1. $ netstat -anp | grep 8080
  2. tcp 0 0 :::8080 :::* LISTEN 27328/./server
  3. tcp 0 0 ::ffff:172.20.22.160:8080 ::ffff:172.28.0.180:9001 ESTABLISHED 27328/./server

从测试结果看,可以成功指定IP和端口。

发表评论

表情:
评论列表 (有 0 条评论,276人围观)

还没有评论,来说两句吧...

相关阅读