77 lines
1.3 KiB
Go
77 lines
1.3 KiB
Go
package server
|
|
|
|
import (
|
|
"errors"
|
|
"net"
|
|
|
|
"git.wntrmute.dev/kyle/kdhcp/config"
|
|
"git.wntrmute.dev/kyle/kdhcp/log"
|
|
)
|
|
|
|
const (
|
|
MaxPacketSize = 512
|
|
)
|
|
|
|
type Server struct {
|
|
Conn net.PacketConn
|
|
Config *config.Config
|
|
}
|
|
|
|
func (s *Server) Close() error {
|
|
return s.Conn.Close()
|
|
}
|
|
|
|
func (s *Server) Bind() (err error) {
|
|
s.Conn, err = BindInterface(s.Config.IP, s.Config.Port, s.Config.Interface)
|
|
return err
|
|
}
|
|
|
|
func (s *Server) ReadFrom() ([]byte, net.Addr, error) {
|
|
b := make([]byte, MaxPacketSize)
|
|
n, addr, err := s.Conn.ReadFrom(b)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
|
|
b = b[:n]
|
|
return b, addr, nil
|
|
}
|
|
|
|
func (s *Server) WriteTo(b []byte, addr net.Addr) error {
|
|
return errors.New("server: not implemented")
|
|
}
|
|
|
|
func (s *Server) AcceptPacket() error {
|
|
packet, addr, err := s.ReadFrom()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
log.Debugf("accepted %d byte packet from %s", len(packet), addr)
|
|
return nil
|
|
}
|
|
|
|
func (s *Server) Listen() {
|
|
for {
|
|
if err := s.AcceptPacket(); err != nil {
|
|
log.Errf("server: error reading packet: %s", err)
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
func New(cfg *config.Config) (*Server, error) {
|
|
srv := &Server{
|
|
Config: cfg,
|
|
}
|
|
|
|
err := srv.Bind()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
log.Infof("server: bound to %s:%s", cfg.Interface, srv.Conn.LocalAddr())
|
|
|
|
return srv, nil
|
|
}
|