本文整理汇总了Python中socket.AF_PACKET属性的典型用法代码示例。如果您正苦于以下问题:Python socket.AF_PACKET属性的具体用法?Python socket.AF_PACKET怎么用?Python socket.AF_PACKET使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类socket
的用法示例。
在下文中一共展示了socket.AF_PACKET属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_mac_address_of_interface
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def get_mac_address_of_interface(interface):
"""
:param interface: The friendly name of a network interface
:return: the MAC address associated with that interface
"""
for k,v in psutil.net_if_addrs().items():
if interface == k:
for item in v:
try:
if item.family == socket.AF_LINK:
return item.address
except AttributeError:
# Linux
if item.family == socket.AF_PACKET:
return item.address
return None
示例2: send_dhcpv6_solicit
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def send_dhcpv6_solicit():
Client_DUID = dhcpv6r.get_duid(macsrc)
request_options = [23, 24]
pkt = dhcpv6r.make_solicit_packet(ethernet_src_mac=macsrc,
ipv6_src=ipv6src_link,
transaction_id=randint(1, 16777215),
client_identifier=Client_DUID,
option_request_list=request_options)
try:
SOCK = socket(AF_PACKET, SOCK_RAW)
SOCK.bind((current_network_interface, 0))
SOCK.send(pkt)
print(Base.c_info + 'Send Solicit request to: [ff02::1:2]:547')
SOCK.close()
except:
print(Base.c_error + 'Do not send Solicit request.')
exit(1)
示例3: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def __init__(self, raw_intf = 'eth1', listen_port=10001):
self.logger = logging.getLogger()
# setup TCP side
self.s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
self.s.bind(('::0', listen_port))
self.s.listen(1)
self.tcp = None
# track current state of TCP side tunnel. 0 = reading size, 1 = reading packet
self.tcp_state = 0
self.tcp_buf = b''
self.tcp_remaining = 0
# setup raw side
self.raw = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003))
self.raw.bind((raw_intf, 0))
# don't block
self.raw.setblocking(0)
示例4: main
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def main():
"""Main function called upon script execution."""
# First open a socket to the kernel. Same one used for sending and receiving.
sk = nl_socket_alloc() # Creates an `nl_sock` instance.
ret = nl_connect(sk, NETLINK_ROUTE) # Create file descriptor and bind socket.
if ret < 0:
reason = errmsg[abs(ret)]
return error('nl_connect() returned {0} ({1})'.format(ret, reason))
# Next we send the request to the kernel.
rt_hdr = rtgenmsg(rtgen_family=socket.AF_PACKET)
ret = nl_send_simple(sk, RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP, rt_hdr, rt_hdr.SIZEOF)
if ret < 0:
reason = errmsg[abs(ret)]
return error('nl_send_simple() returned {0} ({1})'.format(ret, reason))
print('Sent {0} bytes to the kernel.'.format(ret))
# Finally we'll retrieve the kernel's answer, process it, and call any callbacks attached to the `nl_sock` instance.
nl_socket_modify_cb(sk, NL_CB_VALID, NL_CB_CUSTOM, callback, None) # Add callback to the `nl_sock` instance.
ret = nl_recvmsgs_default(sk) # Get kernel's answer, and call attached callbacks.
if ret < 0:
reason = errmsg[abs(ret)]
return error('nl_recvmsgs_default() returned {0} ({1})'.format(ret, reason))
示例5: start
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def start(interface, emu_rx_port=5556, emu_tx_port=5555, msg_id=1073905664):
global __run_server
global __host_socket
# Open socket to send raw frames on ethernet adapter
os.system('ip link set %s promisc on' % interface) # Set to permisucous
# os.system('ethtool -K %s tx off' % interface)
ETH_P_ALL = 3
__host_socket = socket.socket(
socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETH_P_ALL))
__host_socket.bind((interface, 0))
print("Starting Servers")
emu_rx_process = Process(target=rx_from_emulator,
args=(emu_rx_port, interface)).start()
emu_tx_process = Process(
target=rx_from_host, args=(emu_tx_port, msg_id)).start()
try:
while (1):
time.sleep(0.1)
except KeyboardInterrupt:
__run_server = False
emu_rx_process.join()
emu_tx_process.join()
示例6: create_raw_socket
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def create_raw_socket(self):
""" Create row socket(SOCK_RAW type) to listen for traffic
"""
try:
self.raw_socket = socket.socket(
socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0003))
except socket.error, msg:
print "unable to create socket"
print "Error Code %d : Message %s" % (msg[0], msg[1])
sys.exit()
示例7: send
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def send(self, hosts, srcp, gen):
if 'ppp' in self.ifname:
family = socket.AF_INET
proto = socket.IPPROTO_RAW
eth = ''
else:
family = socket.AF_PACKET
proto = ETH_P_IP
eth = ethernet.ETHER(mac2byte(self.smac), mac2byte(self.dmac), ETH_P_IP).pack()
sock = socket.socket(family, socket.SOCK_RAW, proto)
transport = self.__Transport(srcp, 0)
npacket = 0
self.events['send'].wait()
target = hosts[0]
while self.events['send'].isSet():
try:
target = hosts[0] + gen.next()
iph = ip.IP(self.diface, dec2dot(target), self.stype)
except StopIteration:
break
for port_list in self.ports:
for port in range(port_list[0], port_list[1]):
if self.events['send'].isSet():
transport.dstp = port
packet = eth + iph.pack() + self.__Pack(transport, iph.src, iph.dst) #tcph.pack(iph.src, iph.dst)
sock.sendto(packet, (dec2dot(target), 0)) # self.ifname
npacket+=1
if not npacket%self.cooldown[0]:
time.sleep(self.cooldown[1])
else:
break
logging.info('[SEND] Sent: {} packets'.format(npacket))
sock.close()
示例8: sender
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def sender():
sleep(5)
SOCK = socket(AF_PACKET, SOCK_RAW)
SOCK.bind((current_network_interface, 0))
sequence = randint(1, 1000000)
syn_header = tcp.make_syn_header(src_ip_address, dst_ip_address, src_port, dst_port, sequence)
ip_header = ip.make_header(src_ip_address, dst_ip_address, 0, len(syn_header), 6)
eth_header = eth.make_header(src_mac_address, dst_mac_address, 2048)
syn_packet = eth_header + ip_header + syn_header
SOCK.send(syn_packet)
while True:
if response_sequence_number == 0:
sleep(1)
else:
if response_acknowledgement_number == sequence + 1:
break
else:
sleep(1)
sequence += 1
acknowledgment = response_sequence_number + 1
ack_header = tcp.make_ack_header(src_ip_address, dst_ip_address, src_port, dst_port,
sequence, acknowledgment, response_timestamp)
ip_header = ip.make_header(src_ip_address, dst_ip_address, 0, len(ack_header), 6)
eth_header = eth.make_header(src_mac_address, dst_mac_address, 2048)
ack_packet = eth_header + ip_header + ack_header
SOCK.send(ack_packet)
psh_header = tcp.make_psh_header(src_ip_address, dst_ip_address, src_port, dst_port,
sequence, acknowledgment, response_timestamp, data)
ip_header = ip.make_header(src_ip_address, dst_ip_address, len(data), len(psh_header), 6)
eth_header = eth.make_header(src_mac_address, dst_mac_address, 2048)
psh_packet = eth_header + ip_header + psh_header + data
SOCK.send(psh_packet)
SOCK.close()
示例9: arp_reply
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def arp_reply(your_mac_address, your_ip_address, target_mac_address, target_ip_address):
SOCK = socket(AF_PACKET, SOCK_RAW)
SOCK.bind((current_network_interface, 0))
arp_reply = arp.make_response(ethernet_src_mac=your_mac_address,
ethernet_dst_mac=target_mac_address,
sender_mac=your_mac_address, sender_ip=your_ip_address,
target_mac=target_mac_address, target_ip=target_ip_address)
SOCK.send(arp_reply)
SOCK.close()
示例10: send_dhcp_discover
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def send_dhcp_discover():
sleep(1)
base.print_info("Sending DHCP discover packets...")
base.print_info("Delay between DISCOVER packets: ", str(args.delay), " sec.")
base.print_info("Start sending packets: ", str(datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
discover_raw_socket = socket(AF_PACKET, SOCK_RAW)
discover_raw_socket.bind((listen_network_interface, 0))
try:
while True:
client_mac = eth.make_random_mac()
transaction_id = randint(1, 4294967295)
discover_raw_socket.send(dhcp.make_discover_packet(ethernet_src_mac=your_mac_address,
client_mac=client_mac,
transaction_id=transaction_id,
relay_agent_ip=your_ip_address))
transactions[transaction_id] = client_mac
if int(time() - start_time) > args.timeout:
if ack_received:
base.print_success("IP address pool is exhausted: ",
str(datetime.now().strftime("%Y/%m/%d %H:%M:%S")))
else:
base.print_error("DHCP Starvation failed timeout!")
sleep(1)
exit(1)
sleep(int(args.delay))
except KeyboardInterrupt:
base.print_info("Exit")
discover_raw_socket.close()
exit(0)
# endregion
# region Send DHCP request
示例11: Sniffer
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def Sniffer(packetList, e):
logger = multiprocessing.get_logger()
snifferSocket = socket.socket(
socket.AF_PACKET,
socket.SOCK_RAW,
socket.ntohs(0x0003)
)
snifferSocket.bind((options['interface'], 0))
logger.info("Sniffer and process packets, Press Ctrl-C to stop.")
while True:
packets = snifferSocket.recvfrom(65535)
packet = packets[0]
ethernetFrame = EthernetFrame()
ethernetFrame.Decode(packet)
if ethernetFrame.ethProto == 8:
ipPacket = IPv4Packet()
ipPacket.Decode(ethernetFrame.payload)
if ipPacket.ipProtocol == 6:
tcpPacket = TCPPacket()
tcpPacket.Decode(ipPacket.payload)
else:
continue
else:
continue
packetDic = MergeDicts(ethernetFrame.GetEthernetHeaderDic(), ipPacket.GetIpv4HeaderDic(),
tcpPacket.GetTcpHeaderDic())
logger.debug(packetDic)
snifferFilter = Filter(packetDic, options)
if snifferFilter.run() is True:
continue
print packetDic
packetList.append(packetDic)
e.set()
snifferSocket.close()
示例12: _arp_loop
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def _arp_loop(self):
try:
with contextlib.closing(
socket.socket(
socket.AF_PACKET, socket.SOCK_RAW,
socket.htons(ether.ETH_TYPE_ARP))) as packet_socket:
packet_socket.bind((self.interface.device_name,
socket.htons(ether.ETH_TYPE_ARP),
socket.PACKET_BROADCAST,
arp.ARP_HW_TYPE_ETHERNET,
mac_lib.BROADCAST))
self._arp_loop_socket(packet_socket)
except greenlet.GreenletExit:
# suppress thread.kill exception
pass
示例13: enumerate
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def enumerate(self):
super().enumerate()
kernel = (0, 0)
req = struct.pack('@IHHIIB', NLM_HDR_LEN + 1, self.RTM_GETADDR,
NLM_F_REQUEST | NLM_F_DUMP, 1, os.getpid(),
socket.AF_PACKET)
self.socket.sendto(req, kernel)
示例14: test_full
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def test_full(tcp_server, monkeypatch):
r"""Diff of C code (from test_bare()) to test against.
--- test_bare.c 2015-02-08 12:43:15.543135855 -0800
+++ test_full.c 2015-02-08 12:43:08.533183752 -0800
@@ -13,10 +13,11 @@
struct nl_sock *sk = nl_socket_alloc();
nl_connect(sk, NETLINK_ROUTE);
sk->s_fd = fd;
- sk->s_local.nl_pid = 0;
- sk->s_seq_next = 0;
+ sk->s_local.nl_pid = 1234;
+ sk->s_seq_next = 10;
- int ret = nl_send_simple(sk, RTM_GETLINK, 0, NULL, 0);
+ struct rtgenmsg rt_hdr = { .rtgen_family = AF_PACKET, };
+ int ret = nl_send_simple(sk, RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP, &rt_hdr, sizeof(rt_hdr));
printf("Bytes: %d\n", ret);
return 0;
"""
monkeypatch.setattr(libnl.socket_, 'generate_local_port', lambda: 1234)
sk = nl_socket_alloc()
nl_connect(sk, NETLINK_ROUTE)
sk.socket_instance.close()
sk.socket_instance = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.socket_instance.connect(tcp_server.server.server_address)
sk.s_local.nl_pid = 1234
sk.s_seq_next = 10
rt_hdr = rtgenmsg(rtgen_family=socket.AF_PACKET)
assert 20 == nl_send_simple(sk, RTM_GETLINK, NLM_F_REQUEST | NLM_F_DUMP, rt_hdr, rt_hdr.SIZEOF)
assert 1 == len(tcp_server.data)
assert b'FAAAABIABQMKAAAA0gQAABEAAAA=' == base64.b64encode(buffer(tcp_server.data[0]))
nl_socket_free(sk)
示例15: eth_addr
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AF_PACKET [as 别名]
def eth_addr (a) :
b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]) , ord(a[1]) , ord(a[2]), ord(a[3]), ord(a[4]) , ord(a[5]))
return b
#create a AF_PACKET type raw socket (thats basically packet level)
#define ETH_P_ALL 0x0003 /* Every packet (be careful!!!) */