Skip to content

Instantly share code, notes, and snippets.

@zeroFruit
Created October 31, 2020 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeroFruit/75880ac92a3ca6f9a014c3649438f6d8 to your computer and use it in GitHub Desktop.
Save zeroFruit/75880ac92a3ca6f9a014c3649438f6d8 to your computer and use it in GitHub Desktop.
Modeling the Internet from the scratch: Link-layer, LAN, Switch - Code snippet: Switch Forwarding
// Forward receives id of port it receives frame, address of sender
// and frame to send to receiver. Based on id and address it determines whether to
// broadcast frame or forward it to others, otherwise just discard frame.
func (s *Switch) Forward(incoming Id, frame na.Frame) error {
s.Table.Update(incoming, frame.Src)
frm, err := s.frmEnc.Encode(frame)
if err != nil {
return err
}
entry, ok := s.Table.LookupByAddr(frame.Dest)
if !ok {
return s.broadcastExcept(incoming, frm)
}
if entry.Incoming.Equal(incoming) {
log.Printf("discard frame from id: %s, src: %s, dest: %s\n", incoming, frame.Src, frame.Dest)
return nil
}
p := s.PortList[entry.Incoming]
if err := p.Transmit(frm); err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment