File: dhcprequest.py

package info (click to toggle)
python-dpkt 1.9.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,104 kB
  • sloc: python: 14,911; makefile: 23
file content (72 lines) | stat: -rw-r--r-- 1,557 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#!/usr/bin/env python
from __future__ import print_function

import sys
import socket

# Since pcapy is not a requirement of dpkt, test the import and give message
try:
    import pcapy
except ImportError:
    print('Could not import pcapy. Please do a $pip install pcapy')
    sys.exit(1)

# dpkt imports
from dpkt import dhcp
from dpkt import udp
from dpkt import ip
from dpkt import ethernet

# Grab the default interface and use that for the injection
devices = pcapy.findalldevs()
iface_name = devices[0]
print('Auto Setting Interface to: {:s}'.format(iface_name))
interface = pcapy.open_live(iface_name, 65536, 1, 0)

# Get local ip
src_ip = socket.inet_pton(socket.AF_INET, interface.getnet())

# Generate broadcast ip and eth_addr
broadcast_ip = socket.inet_pton(socket.AF_INET, '255.255.255.255')
broadcast_eth_addr = b'\xFF\xFF\xFF\xFF\xFF\xFF'

# build a dhcp discover packet to request an ip
d = dhcp.DHCP(
    xid=1337,
    op=dhcp.DHCPDISCOVER,
    opts=(
        (dhcp.DHCP_OP_REQUEST, b''),
        (dhcp.DHCP_OPT_REQ_IP, b''),
        (dhcp.DHCP_OPT_ROUTER, b''),
        (dhcp.DHCP_OPT_NETMASK, b''),
        (dhcp.DHCP_OPT_DNS_SVRS, b'')
    )
)

# build udp packet
u = udp.UDP(
    dport=67,
    sport=68,
    data=d
)
u.ulen = len(u)

# build ip packet
i = ip.IP(
    dst=broadcast_ip,
    src=src_ip,
    data=u,
    p=ip.IP_PROTO_UDP
)
i.len = len(i)

# build ethernet frame
e = ethernet.Ethernet(
    dst=broadcast_eth_addr,
    data=i
)

# Inject the packet (send it out)
interface.sendpacket(bytes(e))

print('DHCP request sent!')