本文整理匯總了Python中socket.SOCK_RAW屬性的典型用法代碼示例。如果您正苦於以下問題:Python socket.SOCK_RAW屬性的具體用法?Python socket.SOCK_RAW怎麽用?Python socket.SOCK_RAW使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類socket
的用法示例。
在下文中一共展示了socket.SOCK_RAW屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _make_socket
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def _make_socket(iface_name: str, can_fd: bool) -> socket.SocketType:
s = socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
try:
s.bind((iface_name,))
s.setsockopt(socket.SOL_SOCKET, _SO_TIMESTAMP, 1) # timestamping
if can_fd:
s.setsockopt(socket.SOL_CAN_RAW, socket.CAN_RAW_FD_FRAMES, 1)
s.setblocking(False)
if 0 != s.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR):
raise OSError('Could not configure the socket: getsockopt(SOL_SOCKET, SO_ERROR) != 0')
except BaseException:
with contextlib.suppress(Exception):
s.close()
raise
return s
示例2: recv
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def recv(self):
sock = socket.socket(socket.AF_INET,
socket.SOCK_RAW,
socket.IPPROTO_TCP)
sock.bind((self.diface, 0))
sock.settimeout(5)
self.events['recv'].wait()
counter = 0
while self.events['recv'].isSet():
try:
data, sa_ll = sock.recvfrom(65535)
self.queue.put(Extract(data))
counter += 1
if counter==self.count:
self.events['send'].clear()
break
except socket.timeout:
continue
sock.close()
logging.info('[RECV] Received: {} packets'.format(counter))
示例3: recv
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def recv(self):
sock = socket.socket(socket.AF_INET,
socket.SOCK_RAW,
self.stype)
sock.bind(('', self.srcp))
sock.settimeout(5)
self.events['recv'].wait()
counter = 0
while self.events['recv'].isSet():
try:
data, sa_ll = sock.recvfrom(65535)
if self.__CookieCheck(data):
self.queue.put(Extract(data))
counter += 1
if counter==self.count:
self.events['send'].clear()
break
except socket.timeout:
continue
sock.close()
logging.info('[RECV] Received: {} packets'.format(counter))
示例4: do_one
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def do_one(dest_addr, timeout):
"""
Returns either the delay (in seconds) or none on timeout.
"""
icmp = socket.getprotobyname("icmp")
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
except socket.error as xxx_todo_changeme:
(errno, msg) = xxx_todo_changeme.args
if errno == 1:
# Operation not permitted
msg = msg + (
" - Note that ICMP messages can only be sent from processes"
" running as root."
)
raise socket.error(msg)
raise # raise the original error
my_ID = os.getpid() & 0xFFFF
send_one_ping(my_socket, dest_addr, my_ID)
delay = receive_one_ping(my_socket, my_ID, timeout)
my_socket.close()
return delay
示例5: tcp_trace
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def tcp_trace(ip, port, tr_tout, output, collect):
status = {'end': False}
rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
rx.setblocking(0)
rx.settimeout(tr_tout)
rx.bind(('', 0))
print('\n' + R + 'HOPS'.ljust(7) + 'IP'.ljust(17) + 'HOST' + W + '\n')
for ttl in range(1,31):
t = threading.Thread(target=tcp_send(ip, port, ttl, rx, status, tr_tout, output, collect), daemon=True)
t = t.start()
if status['end'] == True:
break
rx.close()
示例6: send_dhcpv6_solicit
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [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)
示例7: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def __init__(self, ip_daddr):
# We're only interested in ICMP, so happy to have this hard coded.
try:
self.icmp_listener = socket.socket(
socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname("icmp")
)
except PermissionError as e:
print(e)
print("Please run as root!")
exit(1)
# TODO: Test Timestamps correctly
try:
SO_TIMESTAMPNS = 35
self.icmp_listener.setsockopt(socket.SOL_SOCKET, SO_TIMESTAMPNS, 1)
except OSError as e:
logging.debug("Timestamps not available, continuing without them for now")
self.ip_daddr = ip_daddr
self.mutex = threading.Lock()
logging.debug("Starting")
self.icmp_packets = dict()
t = threading.Thread(target=self.listener)
t.setDaemon(True)
t.start()
示例8: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def __init__(self, type=ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0): # noqa: E501
self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) # noqa: E501
self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) # noqa: E501
self.iface = iface
if iface is not None:
self.ins.bind((self.iface, type))
if not six.PY2:
try:
# Receive Auxiliary Data (VLAN tags)
self.ins.setsockopt(SOL_PACKET, PACKET_AUXDATA, 1)
self.ins.setsockopt(
socket.SOL_SOCKET,
SO_TIMESTAMPNS,
1
)
self.auxdata_available = True
except OSError:
# Note: Auxiliary Data is only supported since
# Linux 2.6.21
msg = "Your Linux Kernel does not support Auxiliary Data!"
log_runtime.info(msg)
示例9: __init__
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def __init__(self):
# info about non-sdn participants
# TODO: Create a mapping between actual interface IP addresses
# and the corresponding MAC addresses for all the non-SDN participants
# In case of MDS, it is actual mac adresses of these interfaces, in case
# of the superset scheme it is : 1XXXX-nexthop_id
# self.nonSDN_nhip_2_nhmac = {}
try:
self.sock = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(ETH_TYPE_ARP))
self.sock.bind((config.interface, 0))
except socket.error as msg:
logger.error("Can't open socket %s", str(config.interface))
logger.exception('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
raise
示例10: serve
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def serve(self):
server_socket = None
self.serverorclient = 1
try:
common.internal_print("Starting module: {0} on {1}".format(self.get_module_name(), self.config.get("Global", "serverbind")))
server_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
if (self.os_type == common.OS_WINDOWS) or (self.os_type == common.OS_MACOSX):
common.internal_print("This module can be run in client mode only on this operating system.", -1)
self.cleanup()
return
self.comms_socket = server_socket
self.authenticated = False
self.communication_initialization()
self.communication(False)
except KeyboardInterrupt:
self.cleanup()
return
self.cleanup()
return
示例11: connect
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def connect(self):
try:
common.internal_print("Starting client: {0}".format(self.get_module_name()))
server_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
if self.os_type == common.OS_WINDOWS:
# this should give back the default route interface IP
default_host_ip = socket.gethostbyname(socket.gethostname())
server_socket.bind((default_host_ip, 0))
self.server_tuple = (self.config.get("Global", "remoteserverip"), self.ICMP_fake_serverport)
self.comms_socket = server_socket
self.serverorclient = 0
self.authenticated = False
self.communication_initialization()
self.do_hello()
self.communication(False)
except KeyboardInterrupt:
self.do_logoff()
self.cleanup()
raise
self.cleanup()
return
示例12: check
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def check(self):
try:
common.internal_print("Checking module on server: {0}".format(self.get_module_name()))
server_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
if self.os_type == common.OS_WINDOWS:
# this should give back the default route interface IP
default_host_ip = socket.gethostbyname(socket.gethostname())
server_socket.bind((default_host_ip, 0))
self.server_tuple = (self.config.get("Global", "remoteserverip"), self.ICMP_fake_serverport)
self.comms_socket = server_socket
self.serverorclient = 0
self.authenticated = False
self.communication_initialization()
self.do_check()
self.communication(True)
except KeyboardInterrupt:
self.cleanup()
raise
except socket.timeout:
common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
self.cleanup()
return
示例13: sniffer_thread
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def sniffer_thread(target):
sniffer = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
sniffer.bind(("0.0.0.0", 0 ))
sniffer.settimeout(5)
sniffer.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
# continually read in packets and parse their information
while ( 1 ):
try:
raw_buffer = sniffer.recvfrom(65565)[0]
except:
if (SNIFF_MUTEX == 0):
sys.exit(1)
ip_header = raw_buffer[0:20]
dst_port = struct.unpack(">h", raw_buffer[0x32:0x34])[0]
iph = struct.unpack('!BBHHHBBH4s4s' , ip_header)
# Create our IP structure
version_ihl = iph[0]
ihl = version_ihl & 0xF
iph_length = ihl * 4
src_addr = socket.inet_ntoa(iph[8]);
# Create our ICMP structure
buf = raw_buffer[iph_length:iph_length + ctypes.sizeof(ICMP)]
icmp_header = ICMP(buf)
# check for the type 3 and code and within our target subnet
if icmp_header.code == 3 and icmp_header.type == 3 and src_addr == target:
if dst_port not in ports_ident["closed"]:
ports_ident["closed"].append(dst_port)
示例14: addListener
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def addListener(self, addr, port, service):
if self.isBroadcast(addr):
self.etherAddrs[addr] = self.broadcastIpToMac(addr)
elif self.isMulticast(addr):
self.etherAddrs[addr] = self.multicastIpToMac(addr)
else:
# unicast -- we don't know yet which IP we'll want to send to
self.etherAddrs[addr] = None
# Set up the receiving socket and corresponding IP and interface information.
# One receiving socket is required per multicast address.
rx = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
rx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
for interface in self.interfaces:
(ifname, mac, ip, netmask) = self.getInterface(interface)
# Add this interface to the receiving socket's list.
if self.isBroadcast(addr):
rx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
elif self.isMulticast(addr):
packedAddress = struct.pack('4s4s', socket.inet_aton(addr), socket.inet_aton(ip))
rx.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, packedAddress)
# Generate a transmitter socket. Each interface
# requires its own transmitting socket.
if interface not in self.noTransmitInterfaces:
tx = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
tx.bind((ifname, 0))
self.transmitters.append({'relay': {'addr': addr, 'port': port}, 'interface': ifname, 'addr': ip, 'mac': mac, 'netmask': netmask, 'socket': tx, 'service': service})
rx.bind((addr, port))
self.receivers.append(rx)
示例15: create_bt_socket
# 需要導入模塊: import socket [as 別名]
# 或者: from socket import SOCK_RAW [as 別名]
def create_bt_socket(interface=0):
exceptions = []
sock = None
try:
sock = socket.socket(family=socket.AF_BLUETOOTH,
type=socket.SOCK_RAW,
proto=socket.BTPROTO_HCI)
sock.setblocking(False)
sock.setsockopt(socket.SOL_HCI, socket.HCI_FILTER, pack("IIIh2x", 0xffffffff,0xffffffff,0xffffffff,0)) #type mask, event mask, event mask, opcode
try:
sock.bind((interface,))
except OSError as exc:
exc = OSError(
exc.errno, 'error while attempting to bind on '
'interface {!r}: {}'.format(
interface, exc.strerror))
exceptions.append(exc)
except OSError as exc:
if sock is not None:
sock.close()
exceptions.append(exc)
except:
if sock is not None:
sock.close()
raise
if len(exceptions) == 1:
raise exceptions[0]
elif len(exceptions) > 1:
model = str(exceptions[0])
if all(str(exc) == model for exc in exceptions):
raise exceptions[0]
raise OSError('Multiple exceptions: {}'.format(
', '.join(str(exc) for exc in exceptions)))
return sock
###########