kdhcp/server/server.go

63 lines
974 B
Go

package server
import (
"fmt"
"net"
"git.wntrmute.dev/kyle/kdhcp/log"
)
// github.com/insomniacslk/dhcp
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
}
return &Packet{
Data: b[:n],
Addr: addr,
}, nil
}
func NewServer(cfg *Config) (*Server, error) {
srv := &Server{
cfg: cfg,
}
err := srv.Listen()
if err != nil {
return nil, err
}
return srv, nil
}