Skip to content

Commit

Permalink
Return friendlier errors on timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
stapelberg committed Jun 22, 2018
1 parent 683b02b commit 45101b2
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dhcp4client

import (
"bytes"
"fmt"
"hash/fnv"
"math/rand"
"net"
Expand Down Expand Up @@ -143,6 +144,15 @@ func (c *Client) SendDiscoverPacket() (dhcp4.Packet, error) {
return discoveryPacket, c.SendPacket(discoveryPacket)
}

// TimeoutError records a timeout when waiting for a DHCP packet.
type TimeoutError struct {
Timeout time.Duration
}

func (te *TimeoutError) Error() string {
return fmt.Sprintf("no DHCP packet received within %v", te.Timeout)
}

//Retreive Offer...
//Wait for the offer for a specific Discovery Packet.
func (c *Client) GetOffer(discoverPacket *dhcp4.Packet) (dhcp4.Packet, error) {
Expand All @@ -151,12 +161,15 @@ func (c *Client) GetOffer(discoverPacket *dhcp4.Packet) (dhcp4.Packet, error) {
for {
timeout := c.timeout - time.Since(start)
if timeout < 0 {
return dhcp4.Packet{}, syscall.ETIMEDOUT
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}

c.connection.SetReadTimeout(timeout)
readBuffer, source, err := c.connection.ReadFrom()
if err != nil {
if errno, ok := err.(syscall.Errno); ok && errno == syscall.EAGAIN {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
return dhcp4.Packet{}, err
}

Expand Down Expand Up @@ -199,12 +212,15 @@ func (c *Client) GetAcknowledgement(requestPacket *dhcp4.Packet) (dhcp4.Packet,
for {
timeout := c.timeout - time.Since(start)
if timeout < 0 {
return dhcp4.Packet{}, syscall.ETIMEDOUT
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}

c.connection.SetReadTimeout(timeout)
readBuffer, source, err := c.connection.ReadFrom()
if err != nil {
if errno, ok := err.(syscall.Errno); ok && errno == syscall.EAGAIN {
return dhcp4.Packet{}, &TimeoutError{Timeout: c.timeout}
}
return dhcp4.Packet{}, err
}

Expand Down

0 comments on commit 45101b2

Please sign in to comment.