本文整理汇总了Python中socket.IP_MULTICAST_IF属性的典型用法代码示例。如果您正苦于以下问题:Python socket.IP_MULTICAST_IF属性的具体用法?Python socket.IP_MULTICAST_IF怎么用?Python socket.IP_MULTICAST_IF使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类socket
的用法示例。
在下文中一共展示了socket.IP_MULTICAST_IF属性的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_v4
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def init_v4(self):
idx = socket.if_nametoindex(self.interface.name)
self.multicast_address = (WSD_MCAST_GRP_V4, WSD_UDP_PORT)
# v4: member_request (ip_mreqn) = { multicast_addr, intf_addr, idx }
mreq = (
socket.inet_pton(self.family, WSD_MCAST_GRP_V4) +
socket.inet_pton(self.family, self.address) +
struct.pack('@I', idx))
self.recv_socket.setsockopt(
socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
try:
self.recv_socket.bind((WSD_MCAST_GRP_V4, WSD_UDP_PORT))
except OSError:
self.recv_socket.bind(('', WSD_UDP_PORT))
self.send_socket.setsockopt(
socket.IPPROTO_IP, socket.IP_MULTICAST_IF, mreq)
self.send_socket.setsockopt(
socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
self.send_socket.setsockopt(
socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, args.hoplimit)
self.listen_address = (self.address, WSD_HTTP_PORT)
示例2: main
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--ifAddr', help='Send out on the interface with the given address.')
args = parser.parse_args()
msearch = 'M-SEARCH * HTTP/1.1\r\n' \
'HOST:239.255.255.250:1900\r\n' \
'ST:upnp:rootdevice\r\n' \
'MX:2\r\n' \
'MAN:"ssdp:discover"\r\n' \
'\r\n'
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
if args.ifAddr:
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(args.ifAddr))
s.settimeout(2)
s.sendto(msearch.encode('utf-8'), ('239.255.255.250', 1900))
try:
while True:
data, addr = s.recvfrom(65535)
try:
print('%s [%s]' % (socket.gethostbyaddr(addr[0])[0], addr[0]))
except socket.herror:
print(addr[0])
print(data)
except socket.timeout:
pass
示例3: create_socket_ipv4_tx_mcast
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def create_socket_ipv4_tx_mcast(self, multicast_address, port, loopback):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
except IOError as err:
self.warning("Could not create IPv4 UDP socket: %s", err)
return None
self.enable_addr_and_port_reuse(sock)
if self._ipv4_address is not None:
try:
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,
socket.inet_aton(self._ipv4_address))
except IOError as err:
self.warning("Could not set IPv6 multicast interface address %s: %s",
self._ipv4_address, err)
return None
try:
loop_value = 1 if loopback else 0
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop_value)
except IOError as err:
self.warning("Could not set IPv4 multicast loopback value %d: %s", loop_value, err)
return None
try:
sock.connect((multicast_address, port))
except IOError as err:
self.warning("Could not connect UDP socket to address %s port %d: %s",
multicast_address, port, err)
return None
return sock
示例4: _send_discover
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def _send_discover(self, sock, ssdp_mx):
msg = self.MSEARCH_MSG.format(
host=self.SSDP_ADDRESS, port=self.SSDP_PORT, mx=ssdp_mx)
if self.USE_SINGLE_SOCKET:
for addr in self.addresses:
sock.setsockopt(
socket.SOL_IP, socket.IP_MULTICAST_IF,
socket.inet_aton(addr))
sock.sendto(msg, (self.SSDP_ADDRESS, self.SSDP_PORT))
else:
sock.sendto(msg, (self.SSDP_ADDRESS, self.SSDP_PORT))
示例5: run
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def run(self):
# Listen for UDP port 1900 packets sent to SSDP multicast address
print("UPNP Responder Thread started...")
ssdpmc_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Required for receiving multicast
ssdpmc_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ssdpmc_socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(LISTEN_IP))
ssdpmc_socket.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton("239.255.255.250") + socket.inet_aton(LISTEN_IP))
ssdpmc_socket.bind(("239.255.255.250", 1900))
while True:
try:
data, addr = ssdpmc_socket.recvfrom(1024)
except socket.error as e:
if stop_thread == True:
print("UPNP Reponder Thread closing socket and shutting down...")
ssdpmc_socket.close()
return
print ("UPNP Responder socket.error exception occured: {0}".format(e.__str__))
# SSDP M-SEARCH method received - respond to it unicast with our info
if "M-SEARCH" in data.decode('utf-8'):
print("UPNP Responder sending response to {0}:{1}".format(addr[0], addr[1]))
ssdpout_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ssdpout_socket.sendto(self.UPNP_RESPONSE, addr)
ssdpout_socket.close()
示例6: getOutgoingInterface
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def getOutgoingInterface(self):
i = self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF)
return socket.inet_ntoa(struct.pack("@i", i))
示例7: _setInterface
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def _setInterface(self, addr):
i = socket.inet_aton(addr)
self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, i)
return 1
示例8: create_multicast_sock
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def create_multicast_sock(own_ip, remote_addr, bind_to_multicast_addr):
"""Create UDP multicast socket."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(False)
sock.setsockopt(
socket.SOL_IP,
socket.IP_MULTICAST_IF,
socket.inet_aton(own_ip))
sock.setsockopt(
socket.SOL_IP,
socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(remote_addr[0]) +
socket.inet_aton(own_ip))
sock.setsockopt(
socket.IPPROTO_IP,
socket.IP_MULTICAST_TTL, 2)
sock.setsockopt(
socket.IPPROTO_IP,
socket.IP_MULTICAST_IF,
socket.inet_aton(own_ip))
# I have no idea why we have to use different bind calls here
# - bind() with multicast addr does not work with gateway search requests
# on some machines. It only works if called with own ip. It also doesn't
# work on Mac OS.
# - bind() with own_ip does not work with ROUTING_INDICATIONS on Gira
# knx router - for an unknown reason.
if bind_to_multicast_addr:
if platform == "win32":
sock.bind(('', remote_addr[1]))
else:
sock.bind((remote_addr[0], remote_addr[1]))
else:
sock.bind((own_ip, 0))
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
return sock
示例9: set_ipv4_multicast_source_address
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def set_ipv4_multicast_source_address(sock, source_address):
"""Sets the given socket up to send multicast from the specified source.
Ensures the multicast TTL is set to 1, so that packets are not forwarded
beyond the local link.
:param sock: An opened IP socket.
:param source_address: A string representing an IPv4 source address.
"""
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)
sock.setsockopt(
socket.IPPROTO_IP,
socket.IP_MULTICAST_IF,
socket.inet_aton(source_address),
)
示例10: create_socket
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def create_socket(self, channels, ttl, multicast_loop, broadcast, source_address=None):
"Create a UDP multicast socket"
self.sock = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM,
socket.IPPROTO_UDP)
self.sock.setsockopt(socket.IPPROTO_IP,
socket.IP_MULTICAST_TTL,
ttl)
for address, port in channels:
if source_address and ipaddress.IPv4Address(address).is_multicast:
try:
self.sock.setsockopt(socket.SOL_IP,
socket.IP_MULTICAST_IF,
socket.inet_aton(source_address))
print("added membership, interface source address: %s, group: %s" % (source_address, address))
self.sock.setsockopt(socket.SOL_IP,
socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(address) + socket.inet_aton(source_address))
except:
print("failed to add membership, interface source address: %s, group: %s. This is ok for unicast." % (source_address, address))
if multicast_loop is True:
self.sock.setsockopt(socket.IPPROTO_IP,
socket.IP_MULTICAST_LOOP, 1)
if broadcast is True:
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.destinations = [
(address, port)
for address, port in channels
]
IP_PMTUDISC_DO = 2
IP_MTU_DISCOVER = 10
# Set DF flag on IP packet (Don't Fragment) - fragmenting would be bad idea
# it's way better to chunk the packets right.
self.sock.setsockopt(socket.IPPROTO_IP, IP_MTU_DISCOVER, IP_PMTUDISC_DO)
示例11: run
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def run(self):
"""Run the server."""
# Listen for UDP port 1900 packets sent to SSDP multicast address
ssdp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ssdp_socket.setblocking(False)
# Required for receiving multicast
ssdp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ssdp_socket.setsockopt(
socket.SOL_IP,
socket.IP_MULTICAST_IF,
socket.inet_aton(self.host_ip_addr))
ssdp_socket.setsockopt(
socket.SOL_IP,
socket.IP_ADD_MEMBERSHIP,
socket.inet_aton("239.255.255.250") +
socket.inet_aton(self.host_ip_addr))
if self.upnp_bind_multicast:
ssdp_socket.bind(("", 1900))
else:
ssdp_socket.bind((self.host_ip_addr, 1900))
while True:
if self._interrupted:
clean_socket_close(ssdp_socket)
return
try:
read, _, _ = select.select(
[ssdp_socket], [],
[ssdp_socket], 2)
if ssdp_socket in read:
data, addr = ssdp_socket.recvfrom(1024)
else:
# most likely the timeout, so check for interrupt
continue
except socket.error as ex:
if self._interrupted:
clean_socket_close(ssdp_socket)
return
_LOGGER.error("UPNP Responder socket exception occurred: %s",
ex.__str__)
# without the following continue, a second exception occurs
# because the data object has not been initialized
continue
if "M-SEARCH" in data.decode('utf-8', errors='ignore'):
# SSDP M-SEARCH method received, respond to it with our info
resp_socket = socket.socket(
socket.AF_INET, socket.SOCK_DGRAM)
resp_socket.sendto(self.upnp_response, addr)
resp_socket.close()
示例12: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def __init__(self, bindaddress=None):
"""Creates an instance of the Zeroconf class, establishing
multicast communications, listening and reaping threads."""
globals()['_GLOBAL_DONE'] = 0
if bindaddress is None:
self.intf = socket.gethostbyname(socket.gethostname())
else:
self.intf = bindaddress
self.group = ('', _MDNS_PORT)
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
except:
# SO_REUSEADDR should be equivalent to SO_REUSEPORT for
# multicast UDP sockets (p 731, "TCP/IP Illustrated,
# Volume 2"), but some BSD-derived systems require
# SO_REUSEPORT to be specified explicity. Also, not all
# versions of Python have SO_REUSEPORT available. So
# if you're on a BSD-based system, and haven't upgraded
# to Python 2.3 yet, you may find this library doesn't
# work as expected.
#
pass
self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 255)
self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)
try:
self.socket.bind(self.group)
except:
# Some versions of linux raise an exception even though
# the SO_REUSE* options have been set, so ignore it
#
pass
self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(self.intf) + socket.inet_aton('0.0.0.0'))
self.socket.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'))
self.listeners = []
self.browsers = []
self.services = {}
self.cache = DNSCache()
self.condition = threading.Condition()
self.engine = Engine(self)
self.listener = Listener(self)
self.reaper = Reaper(self)
示例13: send
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def send(query,
address=DEFAULT_ADDRESS,
port=DEFAULT_PORT,
ttl=DEFAULT_TTL,
local_only=False,
timeout_s=2):
"""Sends a query to the given multicast socket and returns responses.
Args:
query: The string query to send.
address: Multicast IP address component of the socket to send to.
port: Multicast UDP port component of the socket to send to.
ttl: TTL for multicast messages. 1 to keep traffic in-network.
timeout_s: Seconds to wait for responses.
Returns: A set of all responses that arrived before the timeout expired.
Responses are tuples of (sender_address, message).
"""
# Set up the socket as a UDP Multicast socket with the given timeout.
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
if local_only:
# Set outgoing interface to localhost to ensure no packets leave this host.
sock.setsockopt(
socket.IPPROTO_IP,
socket.IP_MULTICAST_IF,
struct.pack('!L', LOCALHOST_ADDRESS))
sock.settimeout(timeout_s)
sock.sendto(query.encode('utf-8'), (address, port))
# Set up our thread-safe Queue for handling responses.
recv_queue = queue.Queue()
def _handle_responses():
while True:
try:
data, address = sock.recvfrom(MAX_MESSAGE_BYTES)
data = data.decode('utf-8')
except socket.timeout:
recv_queue.put(None)
break
else:
_LOG.debug('Multicast response to query "%s": %s:%s',
query, address[0], data)
recv_queue.put((address[0], str(data)))
# Yield responses as they come in, giving up once timeout expires.
response_thread = threading.Thread(target=_handle_responses)
response_thread.start()
while response_thread.is_alive():
recv_tuple = recv_queue.get()
if not recv_tuple:
break
yield recv_tuple
response_thread.join()
示例14: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import IP_MULTICAST_IF [as 别名]
def __init__(
self,
interfaces=InterfaceChoice.All,
):
"""Creates an instance of the Zeroconf class, establishing
multicast communications, listening and reaping threads.
:type interfaces: :class:`InterfaceChoice` or sequence of ip addresses
"""
# hook for threads
self._GLOBAL_DONE = False
self._listen_socket = new_socket()
interfaces = normalize_interface_choice(interfaces, socket.AF_INET)
self._respond_sockets = []
for i in interfaces:
log.debug('Adding %r to multicast group', i)
try:
self._listen_socket.setsockopt(
socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i))
except socket.error as e:
if get_errno(e) == errno.EADDRINUSE:
log.info(
'Address in use when adding %s to multicast group, '
'it is expected to happen on some systems', i,
)
elif get_errno(e) == errno.EADDRNOTAVAIL:
log.info(
'Address not available when adding %s to multicast '
'group, it is expected to happen on some systems', i,
)
continue
else:
raise
respond_socket = new_socket()
respond_socket.setsockopt(
socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i))
self._respond_sockets.append(respond_socket)
self.listeners = []
self.browsers = {}
self.services = {}
self.servicetypes = {}
self.cache = DNSCache()
self.condition = threading.Condition()
self.engine = Engine(self)
self.listener = Listener(self)
self.engine.add_reader(self.listener, self._listen_socket)
self.reaper = Reaper(self)
self.debug = None