#!/usr/bin/env python
#
#    dhcp_request.py
#    Copyright (C) 2008 Canonical Ltd.
#    Author: Jamie Strandboge <jamie () canonical com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License version 2,
#    as published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

from scapy import *

conf.checkIPaddr=0
iface = "eth0"
timeout = 10

def usage():
    print "Usage: dhcp_request.py <ip>"
    sys.exit(1)

if len(sys.argv) != 2:
    usage()

request_ip = sys.argv[1]

ans = dhcp_request(iface, timeout=timeout)

if not ans:
    print "\nNo server response for DHCPREQUEST after %d seconds" % (timeout)
    sys.exit(0)
#ans.show()

server_ip = ans.sprintf(r"%BOOTP.siaddr%")
server_hw = ans.sprintf(r"%Ether.src%")
offer_ip = ans.sprintf(r"%BOOTP.yiaddr%")

print "\nserver_ip:  %s\nserver_hw:  %s\noffer_ip:   %s" % (server_ip, server_hw, offer_ip)
print "request_ip: %s\n" % (request_ip)

fam,hw = get_if_raw_hwaddr(iface)
ans2 = srp1(Ether(dst="ff:ff:ff:ff:ff:ff",src=hw)/IP(src="0.0.0.0",dst="255.255.255.255")/UDP(sport=68,dport=67)/BOOTP(chaddr=hw)/DHCP(options=[("message-type","request"),("requested_addr", request_ip),("server_id", server_ip),"end"]),iface=iface, timeout=timeout)

if not ans2:
    print "\nNo server response for DHCPREQUEST after %d seconds" % (timeout)
    sys.exit(0)
#ans2.show()

for opt in ans2.payload.payload.payload.payload.options:
    if opt[0] == 'message-type':
        print "\nResponse: %s" % (DHCPTypes[opt[1]])

