Skip to content

Instantly share code, notes, and snippets.

@09zwcbupt
Forked from glacjay/tun-ping-linux.py
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save 09zwcbupt/2fb21705c6eea828c4d9 to your computer and use it in GitHub Desktop.

Select an option

Save 09zwcbupt/2fb21705c6eea828c4d9 to your computer and use it in GitHub Desktop.
import fcntl
import os
import struct
import subprocess
# Some constants used to ioctl the device file. I got them by a simple C
# program.
TUNSETIFF = 0x400454ca
TUNSETOWNER = TUNSETIFF + 2
IFF_TUN = 0x0001
IFF_TAP = 0x0002
IFF_NO_PI = 0x1000
# Open TUN device file.
tap = open('/dev/net/tun', 'r+b')
# Tall it we want a TAP device named tap0.
ifr = struct.pack('16sH', 'tap0', IFF_TAP | IFF_NO_PI)
fcntl.ioctl(tap, TUNSETIFF, ifr)
# Optionally, we want it be accessed by the normal user.
fcntl.ioctl(tap, TUNSETOWNER, 1000)
# Bring it up and assign addresses.
subprocess.check_call('ifconfig tap0 up', shell=True)
# Define a dummy packet
pkt = "\x01\x81\x01\x01\x00\x00\x00\x00\x124Vx\x08\x00E\x00\x00\x1c\x00\x01\x00\x00@\x11j\xbd\x01\x02\x03\x04\x05\x06\x07\x08'\x06\x03\x8f\x00\x08\xc55"
# Write packet into tap device
os.write(tap.fileno(), pkt )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment