Python socket.IPPROTO_IP() Examples

The following are code examples for showing how to use socket.IPPROTO_IP(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: Static-UPnP   Author: nigelb   File: util.py    (license) View Source Project 8 votes vote down vote up
def setup_sockets(self):

    self.sockets = {}
    ip_addresses = get_interface_addresses(self.logger)

    self.ip_addresses = ip_addresses

    multi_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    multi_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    multi_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, self.ttl)

    for ip in ip_addresses:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        mreq=socket.inet_aton(self.address)+socket.inet_aton(ip)
        multi_sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        self.logger.info("Regestering multicast for: %s: %s"%(self.address, ip))
        sock.bind((ip, self.port))

        self.sockets[ip] = sock

    multi_sock.bind(("", self.port))
    self.socks = [self.sockets[x] for x in self.sockets.keys()]
    self.multi_sock = multi_sock 
Example 2
Project: CON-SAI   Author: SSL-Roots   File: multicast.py    (license) View Source Project 7 votes vote down vote up
def __init__(self, group_addr, port):
        bind_addr = '0.0.0.0'

        # Create a IPv4/UDP socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Avoid error 'Address already in use'.
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Construct a membership_request
        membership_request = socket.inet_aton(group_addr) + socket.inet_aton(bind_addr)

        # Send add membership request to socket
        self.sock.setsockopt(socket.IPPROTO_IP, 
                socket.IP_ADD_MEMBERSHIP, membership_request)

        # Bind the socket to an interfaces
        self.sock.bind((bind_addr, port))

        # Set non-blocking receiving mode
        self.sock.setblocking(False)

        self.publisher = rospy.Publisher('/raw_referee', std_msgs.msg.String, queue_size=10) 
Example 3
Project: CoolesSpiel   Author: AlinaGri   File: gameLogic.py    (license) View Source Project 7 votes vote down vote up
def __init__(self, playerCount):
        """
        Initialisierung eines GameLogic
         
        Parameter:      int die maximale Spieleranzahl
        R├╝ckgabewerte:  -
        """
        threading.Thread.__init__(self)
        self.deamon = True

        self.queue = Queue.Queue(0)

        self.playerCount = playerCount
        self.playerConnectedCount = 0
        self.players = []
        self.weaponPositions = []
        self.possibleWeaponPositions = ["140_110", "490_110", "420_300", "220_300", "060_300", "600_300", "420_550", "220_550", "090_490", "550_480", "600_170", "600_040", "350_050", "290_040", "050_180"]
        self.playerPositions = []
        self.game = game.Game(self)

        self.MCAST_GRP = '224.1.1.1'
        self.MCAST_PORT = 5000
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) 
Example 4
Project: ParadoxIP150v2   Author: Tertiush   File: client.py    (Eclipse Public License 1.0) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("localhost", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 5
Project: twampy   Author: nokia   File: twampy.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
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) 
Example 6
Project: CON-SAI   Author: SSL-Roots   File: multicast.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, group_addr, port):
        bind_addr = '0.0.0.0'

        # Create a IPv4/UDP socket
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Avoid error 'Address already in use'.
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Construct a membership_request
        membership_request = socket.inet_aton(group_addr) + socket.inet_aton(bind_addr)

        # Send add membership request to socket
        self.sock.setsockopt(socket.IPPROTO_IP, 
                socket.IP_ADD_MEMBERSHIP, membership_request)

        # Bind the socket to an interfaces
        self.sock.bind((bind_addr, port))

        # Set non-blocking receiving mode
        self.sock.setblocking(False)

        self.publisher = rospy.Publisher('/raw_vision', std_msgs.msg.String, queue_size=10) 
Example 7
Project: AshsSDK   Author: thehappydinoa   File: client.py    (license) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 8
Project: dbus-mqtt   Author: victronenergy   File: client.py    (license) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 9
Project: fdslight   Author: fdslight   File: traffic_pass.py    (license) View Source Project 6 votes vote down vote up
def init_func(self, creator_fd):
        self.__creator_fd = creator_fd
        self.__sent = []

        family = socket.AF_INET

        s = socket.socket(family, socket.SOCK_RAW,
                          socket.IPPROTO_UDP | socket.IPPROTO_ICMP | socket.IPPROTO_UDP | 136)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
        s.setblocking(0)

        self.__socket = s
        self.set_fileno(s.fileno())
        self.register(self.fileno)
        self.add_evt_read(self.fileno)

        return self.fileno 
Example 10
Project: landscape-client   Author: CanonicalLtd   File: test_network.py    (license) View Source Project 6 votes vote down vote up
def test_unplugged(self, mock_ioctl, mock_unpack):
        """
        The link speed for an unplugged interface is reported as 0.
        """
        sock = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_IP)

        # ioctl always succeeds
        mock_unpack.return_value = (65535, False)

        result = get_network_interface_speed(sock, b"eth0")

        mock_ioctl.assert_called_with(ANY, ANY, ANY)
        mock_unpack.assert_called_with("12xHB28x", ANY)

        self.assertEqual((0, False), result) 
Example 11
Project: landscape-client   Author: CanonicalLtd   File: test_network.py    (license) View Source Project 6 votes vote down vote up
def test_get_network_interface_speed_not_supported(self, mock_ioctl):
        """
        Some drivers do not report the needed interface speed. In this case
        an C{IOError} with errno 95 is raised ("Operation not supported").
        If such an error is rasied, report the speed as -1.
        """
        sock = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_IP)
        theerror = IOError()
        theerror.errno = 95
        theerror.message = "Operation not supported"

        # ioctl always raises
        mock_ioctl.side_effect = theerror

        result = get_network_interface_speed(sock, b"eth0")

        mock_ioctl.assert_called_with(ANY, ANY, ANY)

        self.assertEqual((-1, False), result) 
Example 12
Project: landscape-client   Author: CanonicalLtd   File: test_network.py    (license) View Source Project 6 votes vote down vote up
def test_get_network_interface_speed_not_permitted(self, mock_ioctl):
        """
        In some cases (lucid seems to be affected), the ioctl() call is not
        allowed for non-root users. In that case we intercept the error and
        not report the network speed.
        """
        sock = socket.socket(
            socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_IP)
        theerror = IOError()
        theerror.errno = 1
        theerror.message = "Operation not permitted"

        # ioctl always raises
        mock_ioctl.side_effect = theerror

        result = get_network_interface_speed(sock, b"eth0")

        mock_ioctl.assert_called_with(ANY, ANY, ANY)

        self.assertEqual((-1, False), result) 
Example 13
Project: landscape-client   Author: CanonicalLtd   File: network.py    (license) View Source Project 6 votes vote down vote up
def get_fqdn():
    """
    Return the current fqdn of the machine, trying hard to return a meaningful
    name.

    In particular, it means working against a NetworkManager bug which seems to
    make C{getfqdn} return localhost6.localdomain6 for machine without a domain
    since Maverick.
    """
    fqdn = socket.getfqdn()
    if "localhost" in fqdn:
        # Try the heavy artillery
        fqdn = socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET,
                                  socket.SOCK_DGRAM, socket.IPPROTO_IP,
                                  socket.AI_CANONNAME)[0][3]
        if "localhost" in fqdn:
            # Another fallback
            fqdn = socket.gethostname()
    return fqdn 
Example 14
Project: homeassistant   Author: lazcad   File: xiaomi.py    (license) View Source Project 6 votes vote down vote up
def _create_mcast_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        if self._interface != 'any':
            if platform.system() != "Windows":
                sock.bind((self.MULTICAST_ADDRESS, self.MULTICAST_PORT))
            else:
                sock.bind((self._interface, self.MULTICAST_PORT))

            mreq = socket.inet_aton(self.MULTICAST_ADDRESS) + socket.inet_aton(self._interface)
        else:
            sock.bind((self.MULTICAST_ADDRESS, self.MULTICAST_PORT))
            mreq = struct.pack("4sl", socket.inet_aton(self.MULTICAST_ADDRESS), socket.INADDR_ANY)

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        return sock 
Example 15
Project: python2-tracer   Author: extremecoders-re   File: mcast.py    (license) View Source Project 6 votes vote down vote up
def sender(group):
    addrinfo = socket.getaddrinfo(group, None)[0]

    s = socket.socket(addrinfo[0], socket.SOCK_DGRAM)

    # Set Time-to-live (optional)
    ttl_bin = struct.pack('@i', MYTTL)
    if addrinfo[0] == socket.AF_INET: # IPv4
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)
    else:
        s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, ttl_bin)

    while True:
        data = repr(time.time())
        s.sendto(data + '\0', (addrinfo[4][0], MYPORT))
        time.sleep(1) 
Example 16
Project: aioheos   Author: easink   File: aioheosupnp.py    (license) View Source Project 6 votes vote down vote up
def connection_made(self, transport):
            """ Protocol connection made """
            if self._verbose:
                print('Connection made')
            self._transport = transport
            sock = self._transport.get_extra_info('socket')
            # sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.settimeout(2)
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
            sock.bind(('', self._upnp.ssdp_port))

            tmpl = ('M-SEARCH * HTTP/1.1',
                    'Host: ' + self._upnp.ssdp_host + ':' + str(self._upnp.ssdp_port),
                    'Man: "ssdp:discover"',
                    'ST: {}'.format(self._search_target),
                    # 'ST: ssdp:all',
                    'MX: 3',
                    '', '')

            msg = "\r\n".join(tmpl).encode('ascii')
            self._transport.sendto(msg, (self._upnp.ssdp_host, self._upnp.ssdp_port)) 
Example 17
Project: NetPower_TestBed   Author: Vignesh2208   File: basicHostIPCLayer.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, hostID, logFile,sharedBufferArray):
        threading.Thread.__init__(self)

        self.threadCmdLock = threading.Lock()
        self.threadCallbackQueue = {}
        self.threadCallbackLock = threading.Lock()
        self.nPendingCallbacks = 0

        self.threadCmdQueue = []
        self.hostID = hostID
        self.sharedBufferArray = sharedBufferArray
        self.log = logger.Logger(logFile, "Host " + str(hostID) + " IPC Thread")
        self.hostIDtoPowerSimID = None
        self.powerSimIDtohostID = None
        self.attackLayer = None
        self.raw_sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
        self.init_shared_ipc_buffer()

    # self.raw_sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 
Example 18
Project: vivisect-py3   Author: bat-serjo   File: devent.py    (license) View Source Project 6 votes vote down vote up
def setEventCast(self, mcast='224.56.56.56', port=45654, bind='0.0.0.0'):
        '''
        Tie this CobraEventCore to any others which share the same multicast
        ip and port.  This basically creates a ( udp "unreliable" ) "bus" on
        which events are serialized using json.
        '''
        # Setup a UDP casting socket
        self._ce_mcastport = port
        self._ce_mcasthost = mcast
        self._ce_ecastsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._ce_ecastsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._ce_ecastsock.bind((bind,port))

        # Join the multicast IP
        mreq = struct.pack("4sL", socket.inet_aton(mcast), socket.INADDR_ANY)
        self._ce_ecastsock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        thr = threading.Thread(target=self._runSocketListener)
        thr.setDaemon(True)
        thr.start() 
Example 19
Project: aws-iot-python   Author: vjammar   File: client.py    (license) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 20
Project: alexa-hue-bridge   Author: IndigoDomotics   File: discovery.py    (license) View Source Project 6 votes vote down vote up
def run(self):
        try:
            PLUGIN.broadcasterLogger.debug("Broadcaster.run called")
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20)
            start_time = time.time()
            end_time = start_time + (PLUGIN.globals['alexaHueBridge'][self.ahbDevId]['discoveryExpiration'] * 60)
            PLUGIN.broadcasterLogger.debug("Broadcaster.run: sending first broadcast:\n{}".format(self.broadcast_packet))
            while True:
                sock.sendto(self.broadcast_packet, (BCAST_IP, UPNP_PORT))
                for x in range(BROADCAST_INTERVAL):
                    time.sleep(1)
                    # Following code will only time out the Broadcaster Thread if PLUGIN.globals['alexaHueBridge'][self.ahbDevId]['discoveryExpiration'] > 0 (valid values 0 thru 10 inclusive)
                    # A value of zero means 'always on'
                    if PLUGIN.globals['alexaHueBridge'][self.ahbDevId]['discoveryExpiration'] and time.time() > end_time:
                        PLUGIN.broadcasterLogger.debug("Broadcaster thread timed out")
                        self.stop()
                    if self.interrupted:
                        PLUGIN.setDeviceDiscoveryState(False, self.ahbDevId)
                        sock.close()
                        return

        except StandardError, e:
            PLUGIN.broadcasterLogger.error(u"StandardError detected in Broadcaster.Run for '{}'. Line '{}' has error='{}'".format(indigo.devices[self.ahbDevId].name, sys.exc_traceback.tb_lineno, e)) 
Example 21
Project: python   Author: emitter-io   File: paho.py    (license) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 22
Project: TrackBots   Author: RoboCupULaval   File: vision_receiver.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, server_address):

        self.server_address = server_address

        self.logger = logging.getLogger('VisionReceiver')

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.socket.bind(server_address)

        if ip_address(server_address[0]).is_multicast:
            self.socket.setsockopt(socket.IPPROTO_IP,
                                   socket.IP_ADD_MEMBERSHIP,
                                   struct.pack("=4sl", socket.inet_aton(server_address[0]), socket.INADDR_ANY))

        self.field = Field()
        self._detection_frame_queue = queue.Queue()

        self._thread = threading.Thread(target=self.receive_packet, daemon=True) 
Example 23
Project: flux_line_bot   Author: blesscat   File: discover.py    (license) View Source Project 6 votes vote down vote up
def create_sockets(mcst_ipaddr, mcst_port):
        mreq = struct.pack("4sl", socket.inet_aton(mcst_ipaddr),
                           socket.INADDR_ANY)

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                          socket.IPPROTO_UDP)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

        if platform.system() == "Windows":
            s.bind(("", mcst_port))
            return (s, )

        else:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            s.bind((mcst_ipaddr, mcst_port))

            bsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                  socket.IPPROTO_UDP)
            bsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            bsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            bsock.bind(("", 1901))

            return (s, bsock) 
Example 24
Project: vagus   Author: privacore   File: UDPMulticastHandler.py    (license) View Source Project 6 votes vote down vote up
def setup_ipv4_multicast_socket(ifaddrs, if_name, addr):
	#todo: if_name ignored
	s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
	s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s.bind(("", Config.udp_multicast.port))
	
	s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, Config.udp_multicast.ttl)
	s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 0)
	
	mreq = struct.pack("4sl", socket.inet_aton(addr), socket.INADDR_ANY)
	
	s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
	
	s.setblocking(0)
	
	multicast_socket_ipv4.append((s,addr))
	
	return True 
Example 25
Project: cloudcam   Author: revmischa   File: client.py    (license) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 26
Project: sdk-samples   Author: cradlepoint   File: client.py    (license) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 27
Project: scripts   Author: vulnersCom   File: syslogXss.py    (license) View Source Project 6 votes vote down vote up
def runAttack(self, targetList):
        # targetList = [{'ipaddress:':'127.0.0.1', 'port':53, 'payload':'blablabla']
        for counter in range(0, self.replayCount):
            for port in self.bindPorts:
                requestPool = Pool(processes=self.maxProcesses)
                sharedSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                sharedSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                sharedSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
                #sharedSocket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 64)
                try:
                    sharedSocket.bind(('', port))
                    print("Sending packets from port %s" % port)
                    taskList = [(sharedSocket, targetParams.get('ipaddress'), targetParams.get('port'), targetParams.get('payload')) for targetParams in targetList]
                    results = requestPool.starmap(asyncSendPayload, taskList)
                except Exception as e:
                    print("Failed binding port %s: %s" % (port, e))
                print("Closing process pool")
                requestPool.close()
                print("Joining process pool")
                requestPool.join()
                print("Closing shared socket")
                sharedSocket.close()
        return True 
Example 28
Project: HomeWizard-   Author: bramkelder   File: client.py    (license) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("localhost", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 29
Project: Charlie   Author: nxintech   File: sniffer.py    (license) View Source Project 6 votes vote down vote up
def _decode(self):
        try:
            ip = IPHeader(self.ip_frame)
            self.layer[socket.IPPROTO_IP] = ip

            payload_start = ip.header_length * 4

            if ip.protocol == socket.IPPROTO_TCP:
                tcp = TCPHeader(self.ip_frame, ip.header_length * 4)
                self.layer[socket.IPPROTO_TCP] = tcp
                payload_start += tcp.data_offset * 4
            else:
                print("Unsupported IP protocol: %s" % ip.protocol)

        except Exception as e:
            raise ValueError("Failed to decode packet: %s" % e) 
Example 30
Project: tellstick-server-plugins   Author: telldus   File: SSDP.py    (license) View Source Project 6 votes vote down vote up
def discover(self):
		service = "ssdp:all"
		group = ("239.255.255.250", 1900)
		message = "\r\n".join([
			'M-SEARCH * HTTP/1.1',
			'HOST: {0}:{1}',
			'MAN: "ssdp:discover"',
			'ST: {st}','MX: 3','',''])
		sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
		sock.settimeout(5)
		sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
		sock.sendto(message.format(*group, st=service), group)
		while True:
			try:
				response = SSDPResponse(sock.recv(1024))
				if response.type == SSDPResponse.ST_ROOT_DEVICE:
					pass
				elif response.type == SSDPResponse.ST_DEVICE:
					device = Device.fromSSDPResponse(response)
					self.devices[response.uuid] = device
			except socket.timeout:
				break
		self.__discoveryDone() 
Example 31
Project: opendxl-client-python   Author: opendxl   File: client.py    (license) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("localhost", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("localhost", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 32
Project: virtual-hue   Author: flok99   File: htx.py    (license) View Source Project 6 votes vote down vote up
def _startSSDPNotifier(addr):
    msgHeader = [
            'NOTIFY * HTTP/1.1\r\n',
            'HOST: 239.255.255.250:1900\r\n',
            "NTS: ssdp:alive\r\n"
        ]

    msg = ''.join(msgHeader) + gen_ssdp_content(addr, 'NT')

    while True:
        print "Sending M-NOTIFY..."
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
        sock.sendto(msg, (ssdp_addr, ssdp_port))
        sock.close()
        del sock

        time.sleep(6) 
Example 33
Project: PyXiaomiGateway   Author: Danielhiversen   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def _create_mcast_socket(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        if self._interface != 'any':
            if platform.system() != "Windows":
                sock.bind((self.MULTICAST_ADDRESS, self.MULTICAST_PORT))
            else:
                sock.bind((self._interface, self.MULTICAST_PORT))

            mreq = socket.inet_aton(self.MULTICAST_ADDRESS) + socket.inet_aton(self._interface)
        else:
            if platform.system() != "Windows":
                sock.bind((self.MULTICAST_ADDRESS, self.MULTICAST_PORT))
            else:
                sock.bind(('', self.MULTICAST_PORT))
            mreq = struct.pack("4sl", socket.inet_aton(self.MULTICAST_ADDRESS), socket.INADDR_ANY)

        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        return sock 
Example 34
Project: aws-iot-device-sdk-python   Author: aws   File: client.py    (license) View Source Project 6 votes vote down vote up
def _socketpair_compat():
    """TCP/IP socketpair including Windows support"""
    listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    listensock.bind(("127.0.0.1", 0))
    listensock.listen(1)

    iface, port = listensock.getsockname()
    sock1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
    sock1.setblocking(0)
    try:
        sock1.connect(("127.0.0.1", port))
    except socket.error as err:
        if err.errno != errno.EINPROGRESS and err.errno != errno.EWOULDBLOCK and err.errno != EAGAIN:
            raise
    sock2, address = listensock.accept()
    sock2.setblocking(0)
    listensock.close()
    return (sock1, sock2) 
Example 35
Project: pyserver   Author: juhgiyo   File: asyncUdp.py    (license) View Source Project 6 votes vote down vote up
def check_mtu_size(self, hostname, port):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(hostname, port)
        s.setsockopt(socket.IPPROTO_IP, IP_MTU_DISCOVER, IP_PMTUDISC_DO)

        max_mtu = self.MAX_MTU
        try:
            s.send('#' * max_mtu)
        except socket.error:
            option = getattr(socket.IPPROTO_IP, 'IP_MTU', 14)
            max_mtu = s.getsockopt(socket.IPPROTO_IP, option)
        return max_mtu

# Echo udp server test
# def readHandle(sock,addr, data):
#   sock.send(addr[0],addr[1],data)
# server=AsyncUDP(5005,readHandle) 
Example 36
Project: pyvizio   Author: vkorn   File: discovery.py    (license) View Source Project 6 votes vote down vote up
def discover(service, timeout=5, retries=1, mx=3):
    group = ("239.255.255.250", 1900)
    message = "\r\n".join([
        'M-SEARCH * HTTP/1.1',
        'HOST: {0}:{1}',
        'MAN: "ssdp:discover"',
        'ST: {st}', 'MX: {mx}', '', ''])
    socket.setdefaulttimeout(timeout)
    responses = {}
    for _ in range(retries):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        message_bytes = message.format(*group, st=service, mx=mx).encode('utf-8')
        sock.sendto(message_bytes, group)
        while True:
            try:
                response = SSDPResponse(sock.recv(1024))
                responses[response.location] = response
            except socket.timeout:
                break
        return list(responses.values()) 
Example 37
Project: hmv-s16   Author: cmuphyscomp   File: optirx.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def mkdatasock(ip_address=None, multicast_address=MULTICAST_ADDRESS, port=PORT_DATA):
    "Create a data socket."
    ip_address = gethostip() if not ip_address else ip_address
    datasock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    datasock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    datasock.bind((ip_address, port))
    # join a multicast group
    mreq = struct.pack("=4sl", socket.inet_aton(multicast_address), socket.INADDR_ANY)
    datasock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    datasock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFSIZE)
    return datasock 
Example 38
Project: hmv-s16   Author: cmuphyscomp   File: send_mocap_packets.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def make_data_sender_socket(ip_address=None):
    """Create a socket for sending multicast data."""
    ip_address = gethostip() if not ip_address else ip_address
    datasock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
    datasock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    datasock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    datasock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 20)
    
    # print("Binding source socket to %s" % ip_address)
    datasock.bind((ip_address, 0))
    return datasock 
Example 39
Project: twampy   Author: nokia   File: twampy.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def connect(self, server="", port=862, tos=0x88):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, tos)
        self.socket.connect((server, port)) 
Example 40
Project: hostapd-mana   Author: adde88   File: udp.py    (license) View Source Project 5 votes vote down vote up
def getOutgoingInterface(self):
        i = self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF)
        return socket.inet_ntoa(struct.pack("@i", i)) 
Example 41
Project: hostapd-mana   Author: adde88   File: udp.py    (license) View Source Project 5 votes vote down vote up
def _setInterface(self, addr):
        i = socket.inet_aton(addr)
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, i)
        return 1 
Example 42
Project: hostapd-mana   Author: adde88   File: udp.py    (license) View Source Project 5 votes vote down vote up
def getLoopbackMode(self):
        return self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP) 
Example 43
Project: hostapd-mana   Author: adde88   File: udp.py    (license) View Source Project 5 votes vote down vote up
def setLoopbackMode(self, mode):
        mode = struct.pack("b", operator.truth(mode))
        self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, mode) 
Example 44
Project: hostapd-mana   Author: adde88   File: udp.py    (license) View Source Project 5 votes vote down vote up
def getTTL(self):
        return self.socket.getsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL) 
Example 45
Project: hostapd-mana   Author: adde88   File: udp.py    (license) View Source Project 5 votes vote down vote up
def _joinAddr2(self, interface, addr, join):
        addr = socket.inet_aton(addr)
        interface = socket.inet_aton(interface)
        if join:
            cmd = socket.IP_ADD_MEMBERSHIP
        else:
            cmd = socket.IP_DROP_MEMBERSHIP
        try:
            self.socket.setsockopt(socket.IPPROTO_IP, cmd, addr + interface)
        except socket.error, e:
            return failure.Failure(error.MulticastJoinError(addr, interface, *e.args)) 
Example 46
Project: pyaqara   Author: javefang   File: protocol.py    (license) View Source Project 5 votes vote down vote up
def _add_membership(self):
        """private: add multicast membership"""
        _LOGGER.debug("Joining multicast group...")
        sock = self.transport.get_extra_info("socket")
        group = socket.inet_aton(MCAST_ADDR)
        mreq = struct.pack("4sL", group, socket.INADDR_ANY)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _LOGGER.debug("Multicast membership added") 
Example 47
Project: pyNet   Author: mcvavy   File: listener.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, thisNode):
        logging.info('Initializing listener')
        self.thisNode = thisNode
        self.MCAST_PORT = 4242
        self.MCAST_GRP = '192.168.1.255'

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.bind(('', self.MCAST_PORT)) 
Example 48
Project: vmx-docker-lwaftr   Author: Juniper   File: rpc-jet.py    (license) View Source Project 5 votes vote down vote up
def connect(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP)
        self.sock.setsockopt(socket.IPPROTO_IP, 109,1)
        self.sock.connect((self.host, self.port)) 
Example 49
Project: panonoctl   Author: florianl   File: ssdp.py    (license) View Source Project 5 votes vote down vote up
def discover(self):
        ws      = None
        usn     = None
        apiV    = None
        srv     = None
        req =  ('M-SEARCH * HTTP/1.1\r\n' +
                'MX: 10\r\n' +
                'HOST: 239.255.255.250:1900\r\n' +
                'MAN: \"ssdp:discover\"\r\n' +
                'NT: panono:ball-camera\r\n' +
                '\r\n')
        ws = None
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.settimeout(7)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        mcast = struct.pack('4sL', socket.inet_aton('239.255.255.250') , socket.INADDR_ANY)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mcast)
        sock.bind(('', 1900))
        try:
            sock.sendto( req.encode(), ('239.255.255.250', 1900))
        except socket.error as e:
            print(e)
            return (None, None, None)
        for _ in range(5):
            try:
                data, addr = sock.recvfrom(1024)
                if not data: continue
                ws = ssdpNotify().getLocation(data)
                if ws is None: continue
                usn = ssdpNotify().getUsn(data)
                apiV = ssdpNotify().getApiVersion(data)
                srv = ssdpNotify().getSrv(data)
                break
            except socket.error as e:
                print(e)
                break
        sock.close()
        return (ws, usn, apiV, srv) 
Example 50
Project: goodbye-mihome   Author: aluminiumgeek   File: mihome.py    (license) View Source Project 5 votes vote down vote up
def receiver(service='mihome'):
    from plugins import gateway

    assert service in MULTICAST, 'No such service'
    store = get_store()
    address, port = MULTICAST.get(service)
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("0.0.0.0", port))
 
    mreq = struct.pack("=4sl", socket.inet_aton(address), socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, SOCKET_BUFSIZE)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    current = {}

    while True:
        data, _ = sock.recvfrom(SOCKET_BUFSIZE)  # buffer size is 1024 bytes
        print(datetime.now().isoformat(), data)
        if service == 'mihome':
            message = json.loads(data.decode())
            data = json.loads(message['data'])
            if message.get('model') in ('sensor_ht', 'weather.v1') and not sensor_ht.process(conn, cursor, current, message, data):
                continue
            elif message.get('model') == 'magnet':
                magnet.process(store, message, data)
            elif message.get('model') == 'gateway':
                gateway.process(store, message, data)
            current = {}
        elif service == 'yeelight':
            yeelight.process(data.decode())