Search code examples
gomtu

When I read from tcp buffers, which number should I select for the mtu value


Here is my code with golang when I'm ready to read buffer:

func Listen() {
  listen, _ := net.Listen("tcp4", "127.0.0.1:7000")
  defer listen.Close()
  for {
    conn, _ := listen.Accept()
    go handler(&conn)
  }
}

func handler(c *net.Conn) {
  for {
    buf := make([]byte, 1464)
    n, _ := (*c).Read(buf)
    if n == 0 {
      continue
    }
  }
}

The 1464 is my network mtu 1492 - 28 IP Header,so which number should I input here?

My network uses ppoe protocol, so the default is (1518 - 18 - 8) 8 is ppoe protocol header, rasult is 1492, then which number should I input there 1492 or 1464?(1492-28)


Solution

  • In the scheme of things, 1464 vs. 1492 isn't a great deal of difference so pick the bigger one. Maybe add a little headroom!

    If you want super tight buffers of exactly the right size then do something like this

    func handler(c *net.Conn) {
      maxSize:=1464
      for {
        buf := make([]byte, maxSize)
        n, _ := (*c).Read(buf)
        if n == 0 {
          continue
        }
        if n > maxSize {
          maxSize=n
        }
      }
    

    And it will adjust. NB make() is a relatively expensive call so you might like to look at sync.pool or other approaches to manage buffers