Python socket.IPPROTO_UDP() Examples

The following are code examples for showing how to use socket.IPPROTO_UDP(). 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: 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 3
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 4
Project: Static-UPnP   Author: nigelb   File: upnp_reciever.py    (license) View Source Project 6 votes vote down vote up
def send(self, service_descriptor, response_data, REQUEST):
        import ip, udp
        response_packet = udp.Packet(dport=REQUEST[1], sport=self.port, data=response_data)
        ip_packet = ip.Packet(
            dst=REQUEST[0],
            src=service_descriptor.params['ip'],
            data=udp.assemble(response_packet, 0),
            p=socket.IPPROTO_UDP,
            ttl=15

        )

        self.logger.debug(response_packet)
        data = udp.assemble(response_packet, 0)
        self.logger.debug(response_data)
        self.logger.debug(ip_packet)
        self.raw_sock.sendto(ip.assemble(ip_packet, 0), REQUEST.REMOTE) 
Example 5
Project: CyberScan   Author: medbenali   File: inet.py    (license) View Source Project 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 6
Project: hostapd-mana   Author: adde88   File: inet.py    (license) View Source Project 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 7
Project: CVE-2016-6366   Author: RiskSense-Ops   File: inet.py    (license) View Source Project 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 8
Project: networks   Author: delimitry   File: snmp.py    (license) View Source Project 6 votes vote down vote up
def snmp_get(ip, port, oid, version=1, community='public'):
    """SNMP get OID value from SNMP agent with IP"""
    try:
        res = make_snmp_get_oid_request(oid, version=version, community=community)
    except Exception as ex:
        print(ex)
        return
    log('SNMP get OID request:')
    log(res.hex() if PY3 else res.encode('hex'))
    host = ip
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.settimeout(5)
    sock.connect((host, port))
    try:
        sock.send(res)
        response = sock.recv(4096)
        log('Response:')
        log(response.hex() if PY3 else response.encode('hex'))
        log('Parse SNMP:')
        return parse_snmp(response)
    except socket.timeout as ex:
        raise ex
    except Exception as ex:
        print(ex)
    return '', '' 
Example 9
Project: networks   Author: delimitry   File: snmp.py    (license) View Source Project 6 votes vote down vote up
def snmp_get_next(ip, port, oid, version=1, community='public'):
    """SNMP get OID value or subtree of OIDs from SNMP agent with IP"""
    res = make_snmp_get_next_oid_request(oid, version=version, community=community)
    log('SNMP get next OID request:')
    log(res.hex() if PY3 else res.encode('hex'))
    host = ip
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.settimeout(5)
    sock.connect((host, port))
    try:
        sock.send(res)
        response = sock.recv(4096)
        log('Response:')
        log(response.hex() if PY3 else response.encode('hex'))
        log('Parse SNMP:')
        return parse_snmp(response)
    except socket.timeout as ex:
        raise ex
    except Exception as ex:
        raise ex
    return '', '' 
Example 10
Project: zsky   Author: wenguonideshou   File: simdht_worker.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, master, bind_ip, bind_port, max_node_qsize):
        DHTClient.__init__(self, max_node_qsize)

        self.master = master
        self.bind_ip = bind_ip
        self.bind_port = bind_port

        self.process_request_actions = {
            "get_peers": self.on_get_peers_request,
            "announce_peer": self.on_announce_peer_request,
        }

        self.ufd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.ufd.bind((self.bind_ip, self.bind_port))

        timer(RE_JOIN_DHT_INTERVAL, self.re_join_DHT) 
Example 11
Project: dhcpkit_vpp   Author: sjm-steffann   File: config.py    (license) View Source Project 6 votes vote down vote up
def __del__(self):
        """
        Clean up VPP connection
        """
        if not self.vpp or not self.vpp.connected:
            return

        # Set a timeout so we don't hang here
        self.vpp.read_timeout = 10

        logger.debug("Tell VPP we don't want punted packets anymore")
        self.vpp.api.punt_socket(is_add=0,
                                 ipv=6, l4_protocol=socket.IPPROTO_UDP, l4_port=self.listen_port,
                                 pathname=self.name.encode('utf-8'))
        logger.debug("Disconnect from VPP API")
        self.vpp.disconnect() 
Example 12
Project: creator-system-test-framework   Author: CreatorDev   File: constrained_client.py    (license) View Source Project 6 votes vote down vote up
def WaitForAddress(bootstrapAddr, attempts=200, wait=0.1):
    """IPv6 interface takes some time to be ready. Wait until a bind operation succeeds before proceeding."""
    sys.stdout.write("Wait for %s" % (bootstrapAddr,))
    for x in xrange(attempts):
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            sock.bind((bootstrapAddr, 0, 0, 0))
            sock.close()
            # bind succeeded, end loop
            sys.stdout.write("OK\n")
            break
        except:
            # bind failed, wait and try again
            time.sleep(wait)
            sys.stdout.write(".")
            sys.stdout.flush()
    else:
        sys.stdout.write("TIMEOUT\n")
        raise ConstrainedClientError("unable to configure tap interface") 
Example 13
Project: hakkuframework   Author: 4shadoww   File: inet.py    (license) View Source Project 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 14
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 15
Project: pytestlab   Author: sangoma   File: dhcp.py    (license) View Source Project 6 votes vote down vote up
def generate_packet(src, data):
    min_size = ethhdr.min_size + ip4hdr.min_size + udphdr.min_size
    packet = bytearray(len(data) + min_size)

    eth = ethhdr({'src': src,
                  'dst': pnet.HWAddress(u'ff:ff:ff:ff:ff:ff'),
                  'type': pnet.ETH_P_IP},
                 buf=packet)

    ip4 = ip4hdr({'dst': ipaddress.IPv4Address(u'255.255.255.255'),
                  'proto': socket.IPPROTO_UDP,
                  'len': len(data) + ip4hdr.min_size + udphdr.min_size},
                 buf=eth.payload)

    udp = udphdr({'sport': 68,
                  'dport': 67,
                  'len': len(data) + udphdr.min_size},
                 buf=ip4.payload)

    ip4['csum'] = pnet.checksum(ip4.tobytes())
    udp['csum'] = pnet.ipv4_checksum(ip4, udp, data)
    udp.payload = data
    return packet 
Example 16
Project: pytestlab   Author: sangoma   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def bootp_filter(port=68):
    return bpf([
        # Check the udp port number
        bpf_stmt([Op.LD, Op.H, Op.ABS], 0x24),
        bpf_jump([Op.JMP, Op.JEQ, Op.K], port, 0, 7),

        # Check ip fragment offset is 0 to verify TCP
        bpf_stmt([Op.LD, Op.H, Op.ABS], 0x14),
        bpf_jump([Op.JMP, Op.JSET, Op.K], 0x1fff, 5, 0),

        # Check tcp protocol field
        bpf_stmt([Op.LD, Op.B, Op.ABS], 0x17),
        bpf_jump([Op.JMP, Op.JEQ, Op.K], socket.IPPROTO_UDP, 0, 3),

        # Check ethertype field for IPv4
        bpf_stmt([Op.LD, Op.H, Op.ABS], 0x0c),
        bpf_jump([Op.JMP, Op.JEQ, Op.K], pnet.ETH_P_IP, 0, 1),

        bpf_stmt([Op.RET, Op.K], 0xffffffff),
        bpf_stmt([Op.RET, Op.K], 0),
    ]) 
Example 17
Project: networkzero   Author: tjguk   File: test_discovery.py    (license) View Source Project 6 votes vote down vote up
def test_beacon_already_running():
    #
    # NB this one has to run without the beacon fixture
    #
    # Bind a socket on a random port before attempting
    # to start a beacon on that same port.
    #
    port = random.choice(nw0.config.DYNAMIC_PORTS)
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    s.bind(("", port))
    try:
        assert nw0.discovery._beacon is None
        nw0.discovery._start_beacon(port=port)
        assert nw0.discovery._beacon is nw0.discovery._remote_beacon
    finally:
        s.close()
        #
        # Make sure any future beacon use assumes it's not
        # already running.
        #
        nw0.discovery._stop_beacon() 
Example 18
Project: igd-exporter   Author: yrro   File: igd.py    (license) View Source Project 6 votes vote down vote up
def search(timeout):
    '''
    Search for devices implementing WANCommonInterfaceConfig on the network.

    Search ends the specified number of seconds after the last result (if any) was received.

    Returns an iterator of root device URLs.
    '''
    with contextlib.ExitStack() as stack:
        sockets = []
        sockets.append(stack.enter_context(socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)))
        sockets.append(stack.enter_context(socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)))

        for s in sockets:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            if s.family == socket.AF_INET6:
                s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)

            with concurrent.futures.ThreadPoolExecutor(len(sockets)) as ex:
                return itertools.chain.from_iterable(ex.map(lambda s: search_socket(s, timeout, ns['i']), sockets)) 
Example 19
Project: heartbreaker   Author: lokori   File: network.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, config):
        if config.connect_address[2] == 0:
            exit("Destination undefined, exiting!")

        NetworkDispatcher.__init__(self,config)

        self.server = None
        self.server_sock = create_bound_socket(config.proto_num, config.bind_address,True)
        self.server_sock=self.prepare_sock(self.server_sock)
        self.dst=config.connect_address[1:]
        print "Connecting to "+str(self.dst)+" from "+str(config.bind_address)
        if self.proto != socket.IPPROTO_UDP:
            self.server_sock.connect(self.dst)

        self.server = self.NetworkEndpoint(self.server_sock,config=self.config)
        self.server.dst = self.dst
        self.handle_connection() 
Example 20
Project: trex-http-proxy   Author: alwye   File: inet.py    (license) View Source Project 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 21
Project: trex-http-proxy   Author: alwye   File: inet.py    (license) View Source Project 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 22
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 23
Project: nfvOrchestrator   Author: uestcNFVproject   File: encode.py    (license) View Source Project 6 votes vote down vote up
def build_udp_packet(src_ip, dest_ip, src_port, dest_port, data):
    """
    Data needs to encoded as Python bytes. In the case of strings
    this means a bytearray of an UTF-8 encoding
    """

    total_len = len(data) + IPV4_HEADER_LEN_BYTES + UDP_HEADER_LEN_BYTES
    # First we build the IP header
    ip_header, ip_header_pack = build_ipv4_header(total_len, socket.IPPROTO_UDP, src_ip, dest_ip)

    # Build UDP header
    udp_header, udp_header_pack = build_udp_header(src_port, dest_port, ip_header, data)

    udp_packet = ip_header_pack + udp_header_pack + data

    return udp_packet 
Example 24
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 25
Project: sslstrip-hsts-openwrt   Author: adde88   File: inet.py    (license) View Source Project 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 26
Project: scapy-radio   Author: BastilleResearch   File: inet.py    (license) View Source Project 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 27
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 28
Project: IoT-Client   Author: suquark   File: iddp.py    (license) View Source Project 6 votes vote down vote up
def reply(self, hook):
        """
        Reply to discover msg
        :param hook: (msg_dict, ipaddr)
        :return: None
        """
        self.sock.bind(('', self.bc_port))
        while True:
            try:
                data, addr = self.sock.recvfrom(4096)
                # pingback = hook(pack_ip(resolve_msg(data), addr[0]))
                requests.get("http://%s:%d/%s" % (addr[0], 19005, "discovery"))
            except socket.timeout:
                logging.debug("IoTDeviceDiscover Reply timeout")
            self.sock.close()
            socket.setdefaulttimeout(self.timeout)  # for new socket objects
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) 
Example 29
Project: recipe-catalog   Author: inocybe   File: encode.py    (license) View Source Project 6 votes vote down vote up
def build_udp_packet(src_ip, dest_ip, src_port, dest_port, data):
    """
    Data needs to encoded as Python bytes. In the case of strings
    this means a bytearray of an UTF-8 encoding
    """

    total_len = len(data) + IPV4_HEADER_LEN_BYTES + UDP_HEADER_LEN_BYTES
    # First we build the IP header
    ip_header, ip_header_pack = build_ipv4_header(total_len, socket.IPPROTO_UDP, src_ip, dest_ip)

    # Build UDP header
    udp_header, udp_header_pack = build_udp_header(src_port, dest_port, ip_header, data)

    udp_packet = ip_header_pack + udp_header_pack + data

    return udp_packet 
Example 30
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 31
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 32
Project: vagus   Author: privacore   File: UDPMulticastHandler.py    (license) View Source Project 6 votes vote down vote up
def setup_ipv6_multicast_socket(ifaddrs, if_name, addr):
	#todo: if_name ignored
	s = socket.socket(socket.AF_INET6, 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_IPV6, socket.IPV6_MULTICAST_HOPS, Config.udp_multicast.ttl)
	s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0)
	
	mreq = struct.pack("16s16s", socket.inet_pton(socket.AF_INET6,addr), chr(0)*16)
	
	s.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq)
	
	s.setblocking(0)
	
	multicast_socket_ipv6.append((s,addr))
	
	return True 
Example 33
Project: ssbc   Author: banwagong-news   File: simdht_worker.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, master, bind_ip, bind_port, max_node_qsize):
        DHTClient.__init__(self, max_node_qsize)

        self.master = master
        self.bind_ip = bind_ip
        self.bind_port = bind_port

        self.process_request_actions = {
            "get_peers": self.on_get_peers_request,
            "announce_peer": self.on_announce_peer_request,
        }

        self.ufd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.ufd.bind((self.bind_ip, self.bind_port))

        timer(RE_JOIN_DHT_INTERVAL, self.re_join_DHT) 
Example 34
Project: L-Spider   Author: LEXUGE   File: dht_spider.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, master, ip, port, max_node_qsize):
        Thread.__init__(self)
        self.setDaemon(True)

        self.max_node_qsize = max_node_qsize
        self.nid = random_id()
        self.nodes = deque(maxlen=max_node_qsize)

        self.master = master
        self.ip = ip
        self.port = port

        self.process_request_actions = {
            "get_peers": self.on_get_peers_request,
            "announce_peer": self.on_announce_peer_request,
        }

        self.ufd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.ufd.bind((self.ip, self.port))

        timer(RE_JOIN_DHT_INTERVAL, self.re_join_DHT) 
Example 35
Project: ouroboros   Author: pybee   File: test_base_events.py    (license) View Source Project 6 votes vote down vote up
def test_create_datagram_endpoint_ip_addr(self, m_socket):
        def getaddrinfo(*args, **kw):
            self.fail('should not have called getaddrinfo')

        m_socket.getaddrinfo = getaddrinfo
        m_socket.socket.return_value.bind = bind = mock.Mock()
        self.loop.add_reader = mock.Mock()
        self.loop.add_reader._is_coroutine = False

        reuseport_supported = hasattr(socket, 'SO_REUSEPORT')
        coro = self.loop.create_datagram_endpoint(
            lambda: MyDatagramProto(loop=self.loop),
            local_addr=('1.2.3.4', 0),
            reuse_address=False,
            reuse_port=reuseport_supported)

        t, p = self.loop.run_until_complete(coro)
        try:
            bind.assert_called_with(('1.2.3.4', 0))
            m_socket.socket.assert_called_with(family=m_socket.AF_INET,
                                               proto=m_socket.IPPROTO_UDP,
                                               type=m_socket.SOCK_DGRAM)
        finally:
            t.close()
            test_utils.run_briefly(self.loop)  # allow transport to close 
Example 36
Project: tripleo-validations   Author: openstack   File: rogue_dhcp.py    (license) View Source Project 6 votes vote down vote up
def inspect_frame(data):
    eth_type = struct.unpack('!H', data[12:14])[0]
    protocol = ord(data[23])
    src_port = struct.unpack('!H', data[34:36])[0]
    dst_port = struct.unpack('!H', data[36:38])[0]
    msg_type = ord(data[42])
    # Make sure we got a DHCP Offer
    if eth_type == ETH_P_IP \
            and protocol == socket.IPPROTO_UDP \
            and src_port == 67 \
            and dst_port == 68 \
            and msg_type == 2:  # DHCP Boot Reply
        server_ip_address = '.'.join(["%s" % ord(m) for m in
                                      data[26:30]])
        server_hw_address = ":".join(["%02x" % ord(m) for m in
                                      data[6:12]])
        dhcp_servers.append([server_ip_address, server_hw_address]) 
Example 37
Project: scapy-vxlan   Author: p4lang   File: inet.py    (license) View Source Project 6 votes vote down vote up
def post_build(self, p, pay):
        p += pay
        l = self.len
        if l is None:
            l = len(p)
            p = p[:4]+struct.pack("!H",l)+p[6:]
        if self.chksum is None:
            if isinstance(self.underlayer, IP):
                if self.underlayer.len is not None:
                    ln = self.underlayer.len-20
                else:
                    ln = len(p)
                psdhdr = struct.pack("!4s4sHH",
                                     inet_aton(self.underlayer.src),
                                     inet_aton(self.underlayer.dst),
                                     self.underlayer.proto,
                                     ln)
                ck=checksum(psdhdr+p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            elif isinstance(self.underlayer, scapy.layers.inet6.IPv6) or isinstance(self.underlayer, scapy.layers.inet6._IPv6ExtHdr):
                ck = scapy.layers.inet6.in6_chksum(socket.IPPROTO_UDP, self.underlayer, p)
                p = p[:6]+struct.pack("!H", ck)+p[8:]
            else:
                warning("No IP underlayer to compute checksum. Leaving null.")
        return p 
Example 38
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 39
Project: deb-python-eventlet   Author: openstack   File: greendns_test.py    (license) View Source Project 6 votes vote down vote up
def test_getaddrinfo(self):
        greendns.resolve = _make_mock_resolve()
        greendns.resolve.add('example.com', '127.0.0.2')
        greendns.resolve.add('example.com', '::1')
        res = greendns.getaddrinfo('example.com', 'domain')
        addr = ('127.0.0.2', 53)
        tcp = (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, addr)
        udp = (socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP, addr)
        addr = ('::1', 53, 0, 0)
        tcp6 = (socket.AF_INET6, socket.SOCK_STREAM, socket.IPPROTO_TCP, addr)
        udp6 = (socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP, addr)
        filt_res = [ai[:3] + (ai[4],) for ai in res]
        assert tcp in filt_res
        assert udp in filt_res
        assert tcp6 in filt_res
        assert udp6 in filt_res 
Example 40
Project: kakeup   Author: Ventto   File: kakeup.py    (license) View Source Project 6 votes vote down vote up
def main():
    args = __getopt()
    args.port = DEFAULT_PORT if args.port == None else int(args.port)

    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
        sock.bind((HOST, args.port))
    except socket.error as msg:
        print ('Cannot create socket. Error: ' + str(msg[0]) + ') Message:' + str(msg[1]))
        sys.exit()

    __handle_sigs_for(sock)

    wol_found = False
    while True:
        packet = sock.recv(65565)

        if (__wol_pktcheck(packet, args.macaddr, args.ipsrc, args.port)
                and not wol_found):
            print("Kore: <WakeUp>")
            os.system(args.cmd)
            wol_found = True
        else:
            wol_found = False 
Example 41
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 42
Project: maas   Author: maas   File: config.py    (license) View Source Project 6 votes vote down vote up
def _gen_addresses(hostname):
    """Yield IPv4 and IPv6 addresses for `hostname`.

    Yields (ip-version, address) tuples, where ip-version is either 4 or 6.

    Internally this uses `socket.getaddrinfo` and limits resolution to UDP
    datagram sockets.
    """
    for family, _, _, _, addr in socket.getaddrinfo(
            hostname, 0, 0, socket.SOCK_DGRAM, socket.IPPROTO_UDP):
        if family == socket.AF_INET:
            ipaddr, _ = addr
            yield 4, ipaddr
        elif family == socket.AF_INET6:
            ipaddr, _, _, _ = addr
            yield 6, ipaddr


# See `_gen_addresses_where_possible`. 
Example 43
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 44
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 45
Project: pnet   Author: vodik   File: test_serialization.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def test_parse_packet_from_bytes():
    data = bytes.fromhex(
        '4500 008b 0000 4000 3e11 1c78 0a0a 0b14'
        '0ac8 0005 0852 0202 0077 a96b 3c35 343e'
        '4a75 6c20 3239 2031 393a 3439 3a34 3520'
        '7665 6761 3478 3420 5445 4c4e 4554 203a'
        '204c 4f47 3a20 3239 2f30 372f 3230 3137'
        '2031 393a 3439 3a34 352e 3030 3020 5445'
        '4c4e 4554 2028 4329 5230 3143 3030 2028'
        '7573 6572 3a61 646d 696e 296c 6f67 2064'
        '6973 706c 6179 206f 6666 0a'
    )

    ipv4 = pnet.parse('ipv4', data)
    assert ipv4.readonly
    assert ipv4['src'] == IPv4Address('10.10.11.20').packed
    assert ipv4['dst'] == IPv4Address('10.200.0.5').packed
    assert ipv4['p'] == socket.IPPROTO_UDP
    assert ipv4['len'] == 139

    udp = ipv4.parse('udp')
    assert udp.readonly
    assert udp['sport'] == 2130
    assert udp['dport'] == 514
    assert udp['len'] == 119

    payload = udp.payload
    assert payload.readonly
    assert payload == (b'<54>Jul 29 19:49:45 vega4x4 TELNET : LOG: 29/07/2017 '
                       b'19:49:45.000 TELNET (C)R01C00 (user:admin)'
                       b'log display off\n') 
Example 46
Project: pnet   Author: vodik   File: test_serialization.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def test_parse_packet_from_bytearray():
    data = bytearray.fromhex(
        '4500 008b 0000 4000 3e11 1c78 0a0a 0b14'
        '0ac8 0005 0852 0202 0077 a96b 3c35 343e'
        '4a75 6c20 3239 2031 393a 3439 3a34 3520'
        '7665 6761 3478 3420 5445 4c4e 4554 203a'
        '204c 4f47 3a20 3239 2f30 372f 3230 3137'
        '2031 393a 3439 3a34 352e 3030 3020 5445'
        '4c4e 4554 2028 4329 5230 3143 3030 2028'
        '7573 6572 3a61 646d 696e 296c 6f67 2064'
        '6973 706c 6179 206f 6666 0a'
    )

    ipv4 = pnet.parse('ipv4', data)
    assert not ipv4.readonly
    assert ipv4['src'] == IPv4Address('10.10.11.20').packed
    assert ipv4['dst'] == IPv4Address('10.200.0.5').packed
    assert ipv4['p'] == socket.IPPROTO_UDP
    assert ipv4['len'] == 139

    udp = ipv4.parse('udp')
    assert not udp.readonly
    assert udp['sport'] == 2130
    assert udp['dport'] == 514
    assert udp['len'] == 119

    payload = udp.payload
    assert not payload.readonly
    assert payload == (b'<54>Jul 29 19:49:45 vega4x4 TELNET : LOG: 29/07/2017 '
                       b'19:49:45.000 TELNET (C)R01C00 (user:admin)'
                       b'log display off\n') 
Example 47
Project: RSPET   Author: panagiks   File: rspet_client.py    (MIT License) View Source Project 5 votes vote down vote up
def udp_spoof_pck(dest_ip, dest_port, source_ip, source_port, payload):
    """Create and return a spoofed UDP packet.

    Keyword argument(s):
    dest_ip -- the desired destination ip
    dest_port -- the desired destination port
    source_ip -- the desired source ip
    source_port -- the desired source port
    """
    from pinject import UDP, IP
    udp_header = UDP(source_port, dest_port, payload).pack(source_ip, dest_ip)
    ip_header = IP(source_ip, dest_ip, udp_header, IPPROTO_UDP).pack()
    return ip_header+udp_header+payload 
Example 48
Project: RSPET   Author: panagiks   File: __init__.py    (MIT License) View Source Project 5 votes vote down vote up
def pack(self, src, dst, proto=socket.IPPROTO_UDP):
        length = self.length + len(self.payload)
        pseudo_header = struct.pack('!4s4sBBH',
            socket.inet_aton(src), socket.inet_aton(dst), 0, 
            proto, length)
        self.checksum = checksum(pseudo_header)
        packet = struct.pack('!HHHH',
            self.src, self.dst, length, 0)
        return packet 
Example 49
Project: twampy   Author: nokia   File: twampy.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def bind6(self, addr, port, tos, ttl):
        log.debug(
            "bind6(addr=%s, port=%d, tos=%d, ttl=%d)", addr, port, tos, ttl)
        self.socket = socket.socket(
            socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_TCLASS, tos)
        self.socket.setsockopt(
            socket.IPPROTO_IPV6, socket.IPV6_UNICAST_HOPS, ttl)
        self.socket.setsockopt(socket.SOL_SOCKET,   socket.SO_REUSEADDR, 1)
        self.socket.bind((addr, port))
        log.info("Wait to receive test packets on [%s]:%d", addr, port) 
Example 50
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))