package server import ( "fmt" "net" "git.wntrmute.dev/kyle/kdhcp/log" "github.com/insomniacslk/dhcp/dhcpv4" ) type Server struct { cfg *Config conn net.PacketConn } func (srv *Server) Listen() (err error) { if srv.conn != nil { srv.conn.Close() } log.Debugf("attempting to set up packet listener on %s 0.0.0.0:%d", DefaultNetwork, srv.cfg.Port) srv.conn, err = net.ListenPacket(DefaultNetwork, fmt.Sprintf(":%d", srv.cfg.Port)) if err != nil { return err } return nil } func (srv *Server) Close() error { if srv.conn != nil { return srv.conn.Close() } return nil } func (srv *Server) ReadFrom() (*Packet, error) { b := make([]byte, srv.cfg.MaxPacketSize) n, addr, err := srv.conn.ReadFrom(b) if err != nil { return nil, err } packet := &Packet{ Data: b[:n], Addr: addr, } packet.Raw, err = dhcpv4.FromBytes(b[:n]) if err != nil { return packet, err } return packet, nil } func NewServer(cfg *Config) (*Server, error) { srv := &Server{ cfg: cfg, } err := srv.Listen() if err != nil { return nil, err } return srv, nil }