Python socket 模块,SOL_IP 实例源码

我们从Python开源项目中,提取了以下45个代码示例,用于说明如何使用socket.SOL_IP

项目:Proxy46    作者:Macronut    | 项目源码 | 文件源码
def handle(self):
        client_ip = self.client_address[0]

        addr = ''
        server = ''
        try:
            sock = self.connection
            sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)

            odestdata = sock.getsockopt(socket.SOL_IP, 80, 16)
            port, addr_ip = struct.unpack("!xxH4sxxxxxxxx", odestdata)
            addr = socket.inet_ntoa(addr_ip)

            server = reverse(addr)

            print_log('%s connecting %s:%d %d %s' % (client_ip, addr, port, server[0], str(server[1])))

            Proxy[server[0]].proxy(sock, server[1], (addr, port))
        except socket.error, e:
            logging.warn(addr + ':' + str(server) + ':' + str(e))
            sock.close()
项目:twampy    作者:nokia    | 项目源码 | 文件源码
def bind(self, addr, port, tos, ttl, df):
        log.debug(
            "bind(addr=%s, port=%d, tos=%d, ttl=%d)", addr, port, tos, ttl)
        self.socket = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, tos)
        self.socket.setsockopt(socket.SOL_IP,     socket.IP_TTL, ttl)
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind((addr, port))
        if df:
            if (sys.platform == "linux2"):
                self.socket.setsockopt(socket.SOL_IP, 10, 2)
            elif (sys.platform == "win32"):
                self.socket.setsockopt(socket.SOL_IP, 14, 1)
            elif (sys.platform == "darwin"):
                log.error("do-not-fragment can not be set on darwin")
            else:
                log.error("unsupported OS, ignore do-not-fragment option")
        else:
            if (sys.platform == "linux2"):
                self.socket.setsockopt(socket.SOL_IP, 10, 0)
项目:SameKeyProxy    作者:xzhou    | 项目源码 | 文件源码
def getrealdest(self, csock):   
        """
        This method only supports linux 2.4+. 

        Cross platform support coming soon.
        """ 
        try:
            socket.SO_ORIGINAL_DST
        except AttributeError:
            # This is not a defined socket option
            socket.SO_ORIGINAL_DST = 80

        # Use the Linux specific socket option to query NetFilter
        odestdata = csock.getsockopt(socket.SOL_IP, socket.SO_ORIGINAL_DST, 16)

        # Unpack the first 6 bytes, which hold the destination data needed                                
        _, port, a1, a2, a3, a4 = struct.unpack("!HHBBBBxxxxxxxx", odestdata)
        address = "%d.%d.%d.%d" % (a1, a2, a3, a4)

        return address, port
项目:pysnmp    作者:etingof    | 项目源码 | 文件源码
def getRecvFrom(addressType):
        def recvfrom(s, sz):
            _to = None
            data, ancdata, msg_flags, _from = s.recvmsg(sz, socket.CMSG_LEN(sz))
            for anc in ancdata:
                if anc[0] == socket.SOL_IP and anc[1] == socket.IP_PKTINFO:
                    addr = in_pktinfo.from_buffer_copy(anc[2])
                    addr = ipaddress.IPv4Address(memoryview(addr.ipi_addr).tobytes())
                    _to = (str(addr), s.getsockname()[1])
                elif anc[0] == socket.SOL_IPV6 and anc[1] == socket.IPV6_PKTINFO:
                    addr = in6_pktinfo.from_buffer_copy(anc[2])
                    addr = ipaddress.ip_address(memoryview(addr.ipi6_addr).tobytes())
                    _to = (str(addr), s.getsockname()[1])
            return data, addressType(_from).setLocalAddress(_to)

        return recvfrom
项目:pysnmp    作者:etingof    | 项目源码 | 文件源码
def getSendTo(addressType):
        def sendto(s, _data, _to):
            ancdata = []
            if type(_to) == addressType:
                addr = ipaddress.ip_address(_to.getLocalAddress()[0])
            else:
                addr = ipaddress.ip_address(s.getsockname()[0])
            if type(addr) == ipaddress.IPv4Address:
                _f = in_pktinfo()
                _f.ipi_spec_dst = in_addr.from_buffer_copy(addr.packed)
                ancdata = [(socket.SOL_IP, socket.IP_PKTINFO, memoryview(_f).tobytes())]
            elif s.family == socket.AF_INET6 and type(addr) == ipaddress.IPv6Address:
                _f = in6_pktinfo()
                _f.ipi6_addr = in6_addr.from_buffer_copy(addr.packed)
                ancdata = [(socket.SOL_IPV6, socket.IPV6_PKTINFO, memoryview(_f).tobytes())]
            return s.sendmsg([_data], ancdata, 0, _to)

        return sendto
项目:pysnmp    作者:etingof    | 项目源码 | 文件源码
def enablePktInfo(self, flag=1):
        if (not hasattr(self.socket, 'sendmsg') or
                not hasattr(self.socket, 'recvmsg')):
            raise error.CarrierError('sendmsg()/recvmsg() interface is not supported by this OS and/or Python version')

        try:
            if self.socket.family in (socket.AF_INET, socket.AF_INET6):
                self.socket.setsockopt(socket.SOL_IP, socket.IP_PKTINFO, flag)
            if self.socket.family == socket.AF_INET6:
                self.socket.setsockopt(socket.SOL_IPV6, socket.IPV6_RECVPKTINFO, flag)
        except socket.error:
            raise error.CarrierError('setsockopt() for %s failed: %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", sys.exc_info()[1]))

        self._sendto = sockmsg.getSendTo(self.addressType)
        self._recvfrom = sockmsg.getRecvFrom(self.addressType)

        debug.logger & debug.flagIO and debug.logger('enablePktInfo: %s option %s on socket %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", flag and "enabled" or "disabled", self.socket.fileno()))
        return self
项目:pysnmp    作者:etingof    | 项目源码 | 文件源码
def enableTransparent(self, flag=1):
        try:
            if self.socket.family == socket.AF_INET:
                self.socket.setsockopt(
                    socket.SOL_IP, socket.IP_TRANSPARENT, flag
                )
            if self.socket.family == socket.AF_INET6:
                self.socket.setsockopt(
                    socket.SOL_IPV6, socket.IP_TRANSPARENT, flag
                )
        except socket.error:
            raise error.CarrierError('setsockopt() for IP_TRANSPARENT failed: %s' % sys.exc_info()[1])
        except OSError:
            raise error.CarrierError('IP_TRANSPARENT socket option requires superusre previleges')

        debug.logger & debug.flagIO and debug.logger('enableTransparent: %s option IP_TRANSPARENT on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno()))
        return self
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def getSendTo(addressType):
        def sendto(s, _data, _to):
            ancdata = []
            if type(_to) == addressType:
                addr = ipaddress.ip_address(_to.getLocalAddress()[0])
            else:
                addr = ipaddress.ip_address(s.getsockname()[0])
            if type(addr) == ipaddress.IPv4Address:
                _f = in_pktinfo()
                _f.ipi_spec_dst = in_addr.from_buffer_copy(addr.packed)
                ancdata = [(socket.SOL_IP, socket.IP_PKTINFO, memoryview(_f).tobytes())]
            elif s.family == socket.AF_INET6 and type(addr) == ipaddress.IPv6Address:
                _f = in6_pktinfo()
                _f.ipi6_addr = in6_addr.from_buffer_copy(addr.packed)
                ancdata = [(socket.SOL_IPV6, socket.IPV6_PKTINFO, memoryview(_f).tobytes())]
            return s.sendmsg([_data], ancdata, 0, _to)
        return sendto
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def enablePktInfo(self, flag=1):
        if not hasattr(self.socket, 'sendmsg') or \
           not hasattr(self.socket, 'recvmsg'):
            raise error.CarrierError('sendmsg()/recvmsg() interface is not supported by this OS and/or Python version')

        try:
            if self.socket.family in (socket.AF_INET, socket.AF_INET6):
                self.socket.setsockopt(socket.SOL_IP, socket.IP_PKTINFO, flag)
            if self.socket.family == socket.AF_INET6:
                self.socket.setsockopt(socket.SOL_IPV6, socket.IPV6_RECVPKTINFO, flag)
        except socket.error:
            raise error.CarrierError('setsockopt() for %s failed: %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", sys.exc_info()[1]))

        self._sendto = sockmsg.getSendTo(self.addressType)
        self._recvfrom = sockmsg.getRecvFrom(self.addressType)

        debug.logger & debug.flagIO and debug.logger('enablePktInfo: %s option %s on socket %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", flag and "enabled" or "disabled", self.socket.fileno()))
        return self
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def enableTransparent(self, flag=1):
        try:
            if self.socket.family == socket.AF_INET:
                self.socket.setsockopt(
                    socket.SOL_IP, socket.IP_TRANSPARENT, flag
                )
            if self.socket.family == socket.AF_INET6:
                self.socket.setsockopt(
                    socket.SOL_IPV6, socket.IP_TRANSPARENT, flag
                )
        except socket.error:
            raise error.CarrierError('setsockopt() for IP_TRANSPARENT failed: %s' % sys.exc_info()[1])
        except OSError:
            raise error.CarrierError('IP_TRANSPARENT socket option requires superusre previleges')

        debug.logger & debug.flagIO and debug.logger('enableTransparent: %s option IP_TRANSPARENT on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno()))
        return self
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def getSendTo(addressType):
        def sendto(s, _data, _to):
            ancdata = []
            if type(_to) == addressType:
                addr = ipaddress.ip_address(_to.getLocalAddress()[0])
            else:
                addr = ipaddress.ip_address(s.getsockname()[0])
            if type(addr) == ipaddress.IPv4Address:
                _f = in_pktinfo()
                _f.ipi_spec_dst = in_addr.from_buffer_copy(addr.packed)
                ancdata = [(socket.SOL_IP, socket.IP_PKTINFO, memoryview(_f).tobytes())]
            elif s.family == socket.AF_INET6 and type(addr) == ipaddress.IPv6Address:
                _f = in6_pktinfo()
                _f.ipi6_addr = in6_addr.from_buffer_copy(addr.packed)
                ancdata = [(socket.SOL_IPV6, socket.IPV6_PKTINFO, memoryview(_f).tobytes())]
            return s.sendmsg([_data], ancdata, 0, _to)
        return sendto
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def enablePktInfo(self, flag=1):
        if not hasattr(self.socket, 'sendmsg') or \
           not hasattr(self.socket, 'recvmsg'):
            raise error.CarrierError('sendmsg()/recvmsg() interface is not supported by this OS and/or Python version')

        try:
            if self.socket.family in (socket.AF_INET, socket.AF_INET6):
                self.socket.setsockopt(socket.SOL_IP, socket.IP_PKTINFO, flag)
            if self.socket.family == socket.AF_INET6:
                self.socket.setsockopt(socket.SOL_IPV6, socket.IPV6_RECVPKTINFO, flag)
        except socket.error:
            raise error.CarrierError('setsockopt() for %s failed: %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", sys.exc_info()[1]))

        self._sendto = sockmsg.getSendTo(self.addressType)
        self._recvfrom = sockmsg.getRecvFrom(self.addressType)

        debug.logger & debug.flagIO and debug.logger('enablePktInfo: %s option %s on socket %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", flag and "enabled" or "disabled", self.socket.fileno()))
        return self
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def enableTransparent(self, flag=1):
        try:
            if self.socket.family == socket.AF_INET:
                self.socket.setsockopt(
                    socket.SOL_IP, socket.IP_TRANSPARENT, flag
                )
            if self.socket.family == socket.AF_INET6:
                self.socket.setsockopt(
                    socket.SOL_IPV6, socket.IP_TRANSPARENT, flag
                )
        except socket.error:
            raise error.CarrierError('setsockopt() for IP_TRANSPARENT failed: %s' % sys.exc_info()[1])
        except OSError:
            raise error.CarrierError('IP_TRANSPARENT socket option requires superusre previleges')

        debug.logger & debug.flagIO and debug.logger('enableTransparent: %s option IP_TRANSPARENT on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno()))
        return self
项目:pyserver    作者:juhgiyo    | 项目源码 | 文件源码
def handle_close(self):

        try:
            delete_set = self.getgrouplist()
            for multicast_addr in delete_set:
                self.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP,
                                socket.inet_aton(multicast_addr) + socket.inet_aton('0.0.0.0'))
                if self.callback_obj is not None:
                    self.callback_obj.on_leave(self, multicast_addr)
            with self.lock:
                self.multicastSet = Set([])
        except Exception as e:
            print e

        print 'asyncUdp close called'
        asyncore.dispatcher.close(self)
        AsyncController.instance().discard(self)
        try:
            if self.callback_obj is not None:
                self.callback_obj.on_stopped(self)
        except Exception as e:
            print e
            traceback.print_exc()

    # noinspection PyMethodOverriding
项目:dnsdiag    作者:farrokhi    | 项目源码 | 文件源码
def sendto(self, *args, **kwargs):
        global _ttl
        if _ttl:
            self.setsockopt(socket.SOL_IP, socket.IP_TTL, _ttl)
        super(CustomSocket, self).sendto(*args, **kwargs)
项目:CyberScan    作者:medbenali    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:honeypot    作者:fabio-d    | 项目源码 | 文件源码
def getoriginaldest(self):
        SO_ORIGINAL_DST = 80
        odestdata = self.request.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16)
        _, port, a1, a2, a3, a4 = struct.unpack("!HHBBBBxxxxxxxx", odestdata)
        address = "%d.%d.%d.%d" % (a1, a2, a3, a4)
        return address, port
项目:CVE-2016-6366    作者:RiskSense-Ops    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
项目:hakkuframework    作者:4shadoww    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:pynetsim    作者:jjo-sec    | 项目源码 | 文件源码
def start(self):
        """
        Spin up the TCP listener

        :return: None
        """
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
            self.sock.bind((self.listen_host, self.listen_port))
            self.sock.listen(1)
            self.sock.settimeout(10)
        except Exception as e:
            log.exception(e)
            self.shutdown()
            return
        log.debug("Started TCP Socket Listener")
        while True:
            try:
                conn, addr = self.sock.accept()
                dst = conn.getsockopt(socket.SOL_IP, 80, 16)
                srv_port, srv_ip = struct.unpack("!2xH4s8x", dst)
                srv_ip = socket.inet_ntoa(srv_ip)
                log.debug("New connection from {}:{} => {}:{}".format(addr[0], addr[1], srv_ip, srv_port))
                future = self.pool.submit(self.handle_connection, conn, addr)
                self.futures[future] = conn
                future.add_done_callback(self.conn_completed)
            except socket.timeout:
                pass
项目:heartbreaker    作者:lokori    | 项目源码 | 文件源码
def handle_accept(self):
        pair = self.accept()
        if pair is None:
            pass
        else:
            client_sock, addr = pair
            domain, srv_host, srv_port = self.dst
            if srv_port == 0:
                dst=client_sock.getsockopt(socket.SOL_IP, 80, 16)
                srv_port, srv_ip = struct.unpack("!2xH4s8x", dst)
                srv_host = socket.inet_ntoa(srv_ip)

            client_sock = self.prepare_sock(client_sock, srv_host)
            print 'Incoming connection from %s' % repr(addr)
            print 'Outgoing connection to %s:%d' %(srv_host, srv_port)

            server_sock = create_bound_socket(self.proto,self.bindaddr,True)

            server_sock=self.prepare_sock(server_sock)
            self.prepare_sock(server_sock)

            try:
                server_sock.connect((srv_host, srv_port))
            except Exception,e:
                print "Connection failed"
                client_sock.close()
                server_sock.close()
                return
            self.client=self.NetworkEndpoint(client_sock, config=self.config)
            self.server=self.NetworkEndpoint(server_sock, config=self.config)
            self.server.meet(self.client)
            self.handle_connection()
项目:microProxy    作者:mike820324    | 项目源码 | 文件源码
def _linux_get_dest_addr(self):  # pragma: no cover
        src_stream = self.context.src_stream
        sock_opt = src_stream.socket.getsockopt(socket.SOL_IP,
                                                self.SO_ORIGINAL_DST,
                                                16)
        _, port, a1, a2, a3, a4 = struct.unpack("!HHBBBBxxxxxxxx", sock_opt)
        address = "%d.%d.%d.%d" % (a1, a2, a3, a4)
        return (address, port)
项目:xknx    作者:XKNX    | 项目源码 | 文件源码
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.
        # - bind() with own_ip does not work with ROUTING_INDICATIONS on Gira
        #   knx router - for an unknown reason.
        if bind_to_multicast_addr:
            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
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:scapy-bpf    作者:guedou    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:scapy-radio    作者:BastilleResearch    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:isf    作者:w3h    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def getRecvFrom(addressType):
        def recvfrom(s, sz):
            _to = None
            data, ancdata, msg_flags, _from = s.recvmsg(sz, socket.CMSG_LEN(sz))
            for anc in ancdata:
                if anc[0] == socket.SOL_IP and anc[1] == socket.IP_PKTINFO:
                    addr = in_pktinfo.from_buffer_copy(anc[2])
                    addr = ipaddress.IPv4Address(memoryview(addr.ipi_addr).tobytes())
                    _to = (str(addr), s.getsockname()[1])
                elif anc[0] == socket.SOL_IPV6 and anc[1] == socket.IPV6_PKTINFO:
                    addr = in6_pktinfo.from_buffer_copy(anc[2])
                    addr = ipaddress.ip_address(memoryview(addr.ipi6_addr).tobytes())
                    _to = (str(addr), s.getsockname()[1])
            return data, addressType(_from).setLocalAddress(_to)
        return recvfrom
项目:beremiz    作者:nucleron    | 项目源码 | 文件源码
def close(self):
        """Ends the background threads, and prevent this instance from
        servicing further queries."""
        if globals()['_GLOBAL_DONE'] == 0:
            globals()['_GLOBAL_DONE'] = 1
            self.notifyAll()
            self.engine.notify()
            self.unregisterAllServices()
            self.socket.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP, socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'))
            self.socket.close()

# Test a few module features, including service registration, service
# query (for Zoe), and service unregistration.
项目:airmtp    作者:shezi    | 项目源码 | 文件源码
def setUdpSocketForMulticastReceive(sock, multicastGroupTuple, ipAddressStrOfMulticastInterface):
    sock.bind(("", multicastGroupTuple[1]))
    sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(multicastGroupTuple[0]) + socket.inet_aton(ipAddressStrOfMulticastInterface))


#
# gets the IP address (as string) of local hostname
#
项目:scapy-vxlan    作者:p4lang    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:python-proxy    作者:qwj    | 项目源码 | 文件源码
def correct_header(self, header, auth, sock, **kw):
        try:
            buf = sock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16)
            assert len(buf) == 16
            remote = (socket.inet_ntoa(buf[4:8]), int.from_bytes(buf[2:4], 'big'))
            assert sock.getsockname() != remote
        except Exception:
            return False
        return auth and header == auth[:1] or not auth
项目:python-proxy    作者:qwj    | 项目源码 | 文件源码
def parse(self, reader, auth, authtable, sock, **kw):
        if auth:
            if (yield from reader.read_n(len(auth)-1)) != auth[1:]:
                raise Exception('Unauthorized Redir')
            authtable.set_authed()
        buf = sock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16)
        return socket.inet_ntoa(buf[4:8]), int.from_bytes(buf[2:4], 'big'), b''
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def getRecvFrom(addressType):
        def recvfrom(s, sz):
            _to = None
            data, ancdata, msg_flags, _from = s.recvmsg(sz, socket.CMSG_LEN(sz))
            for anc in ancdata:
                if anc[0] == socket.SOL_IP and anc[1] == socket.IP_PKTINFO:
                    addr = in_pktinfo.from_buffer_copy(anc[2])
                    addr = ipaddress.IPv4Address(memoryview(addr.ipi_addr).tobytes())
                    _to = (str(addr), s.getsockname()[1])
                elif anc[0] == socket.SOL_IPV6 and anc[1] == socket.IPV6_PKTINFO:
                    addr = in6_pktinfo.from_buffer_copy(anc[2])
                    addr = ipaddress.ip_address(memoryview(addr.ipi6_addr).tobytes())
                    _to = (str(addr), s.getsockname()[1])
            return data, addressType(_from).setLocalAddress(_to)
        return recvfrom
项目:PyQYT    作者:collinsctk    | 项目源码 | 文件源码
def __init__(self, type = ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0):
        self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
        self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
        if iface is not None:
            self.ins.bind((iface, type))
项目:pyserver    作者:juhgiyo    | 项目源码 | 文件源码
def join(self, multicast_addr):
        with self.lock:
            if multicast_addr not in self.multicastSet:
                self.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
                                socket.inet_aton(multicast_addr) + socket.inet_aton(self.bind_addr))
                self.multicastSet.add(multicast_addr)
                if self.callback_obj is not None:
                    self.callback_obj.on_join(self, multicast_addr)

    # for RECEIVER to stop receiving datagram from the multicast group
项目:pyserver    作者:juhgiyo    | 项目源码 | 文件源码
def leave(self, multicast_addr):
        with self.lock:
            try:
                if multicast_addr in self.multicastSet:
                    self.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP,
                                    socket.inet_aton(multicast_addr) + socket.inet_aton('0.0.0.0'))
                    self.multicastSet.discard(multicast_addr)
                    if self.callback_obj is not None:
                        self.callback_obj.on_leave(self, multicast_addr)
            except Exception as e:
                print e
项目:legos.nettools    作者:Legobot    | 项目源码 | 文件源码
def one_ping(self, ip, port, identifier, sequence, ttl, timeout):
        #prepare result dict
        result = {'error': None}

        #create sockets
        ins = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp)
        #bind and set timeout for IN socket
        ins.bind(("", port))
        ins.settimeout(timeout)
        #set TTL for OUT socket
        outs.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)

        #create packet and send it
        #print('sending to', ip, 'packet with', identifier, sequence)
        packet = messages.EchoRequest(identifier = identifier, sequence = sequence)
        outs.sendto(packet.pack(), (ip, port))

        #get answer and time it
        start = datetime.datetime.now()
        try:
            s = time.time()
            while time.time() - s < timeout:
                a  = ins.recvfrom(1024)[0]
                ip_header = ip_m.Header(a[:20])
                outp = messages.types[a[20]]()
                outp.unpack(a[20:])
                if (
                        (
                            #handle errors
                            type(outp) in messages.error_messages and
                            #cover not specification complient routers
                            outp.original_message is not None and
                            identifier == outp.original_message.identifier and
                            sequence == outp.original_message.sequence
                        )
                        or
                        (
                            #handle normal responses
                            type(outp) in messages.reply_messages and
                            identifier == outp.identifier and
                            sequence == outp.sequence
                        )
                    ):
                        if type(outp) == messages.EchoReply:
                            self.result['on'] = True
                            delta = datetime.datetime.now() - start
                            self.result['times'].append(delta.seconds * 1000000 + delta.microseconds)
                            self.result['responses'].append((ip_header, outp))
                            break
        except socket.timeout as e:
            self.result['packet_loss'] += 1
项目:pyimc    作者:oysstu    | 项目源码 | 文件源码
def get_multicast_socket(sock=None):
    if not sock:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    sock.settimeout(0.001)

    # set multicast interface to any local interface
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton('0.0.0.0'))

    # Enable multicast, TTL should be <32 (local network)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 5)

    # Allow reuse of addresses
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Allow receiving multicast broadcasts (subscribe to multicast group)
    try:
        mreq = struct.pack('4sL', socket.inet_aton(multicast_ip), socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        # Do not loop back own messages
        sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 0)
    except OSError as e:
        logger.error('Unable to obtain socket with multicast enabled.')
        raise e

    port = None
    for i in range(30100, 30105):
        try:
            # Binding to 0.0.0.0 results in multiple messages if there is multiple interfaces available
            # Kept as-is to avoid losing messages
            sock.bind(('0.0.0.0', i))
            port = i
            break
        except OSError as e:
            # Socket already in use without SO_REUSEADDR enabled
            continue

    if not port:
        raise RuntimeError('No IMC multicast ports free on local interface.')

    return sock
项目:beremiz    作者:nucleron    | 项目源码 | 文件源码
def __init__(self, bindaddress=None):
        """Creates an instance of the Zeroconf class, establishing
        multicast communications, listening and reaping threads."""
        globals()['_GLOBAL_DONE'] = 0
        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 Exception:
            # 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 Exception:
            # Some versions of linux raise an exception even though
            # the SO_REUSE* options have been set, so ignore it
            #
            pass

        if self.intf is not None:
            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)
项目:pyserver    作者:juhgiyo    | 项目源码 | 文件源码
def __init__(self, port, callback_obj, ttl=1, enable_loopback=False, bind_addr=''):
        asyncore.dispatcher.__init__(self)
        # self.lock = threading.RLock()
        self.MAX_MTU = 1500
        self.callback_obj = None
        self.port = port
        self.multicastSet = Set([])
        self.lock = threading.RLock()
        self.ttl = ttl
        self.enable_loopback = enable_loopback
        if callback_obj is not None and isinstance(callback_obj, IUdpCallback):
            self.callback_obj = callback_obj
        else:
            raise Exception('callback_obj is None or not an instance of IUdpCallback class')
        try:
            self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.set_reuse_addr()
            try:
                socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            except AttributeError:
                pass  # Some systems don't support SO_REUSEPORT

            # for both SENDER and RECEIVER to restrict the region
            self.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.ttl)
            # for SENDER to choose whether to use loop back
            if self.enable_loopback:
                self.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
            else:
                self.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)

            self.bind_addr = bind_addr
            if self.bind_addr is None or self.bind_addr == '':
                self.bind_addr = socket.gethostbyname(socket.gethostname())
                # for both SENDER and RECEIVER to bind to specific network adapter
            self.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(self.bind_addr))

            # for RECEIVE to receive from multiple multicast groups
            self.bind(('', port))
        except Exception as e:
            print e
            traceback.print_exc()
        self.sendQueue = Queue.Queue()  # thread-safe queue
        AsyncController.instance().add(self)
        if self.callback_obj is not None:
            self.callback_obj.on_started(self)

    # Even though UDP is connectionless this is called when it binds to a port
项目:homeassistant    作者:NAStools    | 项目源码 | 文件源码
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))

        ssdp_socket.bind(("239.255.255.250", 1900))

        while True:
            if self._interrupted:
                clean_socket_close(ssdp_socket)
                return

            try:
                read, _, _ = select.select(
                    [self._interrupted_read_pipe, ssdp_socket], [],
                    [ssdp_socket])

                if self._interrupted_read_pipe in read:
                    # Implies self._interrupted is True
                    clean_socket_close(ssdp_socket)
                    return
                elif ssdp_socket in read:
                    data, addr = ssdp_socket.recvfrom(1024)
                else:
                    continue
            except socket.error as ex:
                if self._interrupted:
                    clean_socket_close(ssdp_socket)
                    return

                _LOGGER.error("UPNP Responder socket exception occured: %s",
                              ex.__str__)

            if "M-SEARCH" in data.decode('utf-8'):
                # 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()