Exemplo n.º 1
0
def is_valid_ipv4(string):
    ''''
    >>> is_valid_ipv4('127.0.0.1')
    True

    >>> is_valid_ipv4('192.168.1.1')
    True

    >>> is_valid_ipv4('255.255.255')
    False
    '''
    # http://stackoverflow.com/questions/319279/
    # how-to-validate-ip-address-in-python
    import socket
    try:
        socket.inet_pton(socket.AF_INET, string)
    except AttributeError:  # no inet_pton here, sorry
        try:
            socket.inet_aton(string)
        except socket.error:
            return False
        return string.count('.') == 3
    except socket.error:  # not a valid address
        return False
    return True
Exemplo n.º 2
0
def validate_ipv4(ip_text):
    try:
        socket.inet_aton(ip_text)
    except socket.error:
        return False
    else:
        return True
Exemplo n.º 3
0
def receiver():
    # create a UDP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    # allow multiple sockets to use the same PORT number
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Bind to the port that we know will receive multicast data
    #bind一般用于服务器绑定、监听本地IP和端口,只可以可以绑定本机所具有的IP和端口
    #但在组播中bind应该设置为监听组播IP和其端口,但bind无法设置为绑定、监听非本机的IP(保留IP也不可以被设置为监听对象)
    #所以在组播中必须bind所有ip,和对应组播的端口号
    sock.bind(('0.0.0.0', MYPORT))#留空也可以
    # tell the kernel that we are a multicast socket
    # sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
    # Tell the kernel that we want to add ourselves to a multicast group
    # The address for the multicast group is the third param
    #加入组播组
    status = sock.setsockopt(socket.IPPROTO_IP,
                             socket.IP_ADD_MEMBERSHIP,
                             socket.inet_aton(MYGROUP) + socket.inet_aton(SENDERIP));

    sock.setblocking(0)
    # ts = time.time()
    while 1:
        try:
            data, addr = sock.recvfrom(1024)
        except socket.error, e:
            pass
        else:
            print "Receive data!"

            print "TIME:", time.time()
            print "FROM: ", addr
            print "DATA: ", data
Exemplo n.º 4
0
def create_socket(multicast_ip, port, local_ip):
    # create a UDP socket
    my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    # allow reuse of addresses
    my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # set multicast interface to local_ip
    my_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(local_ip))

    # Set multicast time-to-live to 1
    # This is to stop data from escaping the local network
    my_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)

    # Construct a membership request...tells router what multicast group we want to subscribe to
    membership_request = socket.inet_aton(multicast_ip) + socket.inet_aton(local_ip)

    # Send add membership request to socket
    # See http://www.tldp.org/HOWTO/Multicast-HOWTO-6.html for explanation of sockopts
    my_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership_request)

    # Bind the socket to an interface.
    # If you bind to a specific interface on the Mac or Linux, no multicast data will arrive
    # If you try to bind to all interfaces on Windows, no multicast data will arrive
    if sys.platform.startswith("darwin") or sys.platform.startswith("linux"):
        my_socket.bind(("0.0.0.0", port))
    else:
        my_socket.bind((local_ip, port))
    return my_socket
def check_argument_input(argument_input_list):

    if len(argument_input_list) != 2:
        print 'Usage : python {} [IP:PORT]' .format(argument_input_list[0])
        sys.exit(1)
    elif ":" not in argument_input_list[1]:
        print 'Usage : [IP:PORT] ({})' .format(argument_input_list[1])
        sys.exit(1)
    elif argument_input_list[1].count(':') > 1:
        print 'Usage : [IP:PORT] ({})' .format(argument_input_list[1])
        sys.exit(1)

    host_name_and_port = argument_input_list[1].split(":")

    if not host_name_and_port[0] or \
            not host_name_and_port[1]:
        print 'Usage : python {} [IP:PORT]' .format(argument_input_list[0])
        sys.exit(1)

    if not host_name_and_port[1].isdigit() or \
        int(host_name_and_port[1]) < 0 or \
            int(host_name_and_port[1]) > 65535:
        print 'Please enter a valid port number : ({})' .format(host_name_and_port[1])
        sys.exit(1)

    try:
        socket.inet_aton(host_name_and_port[0])
    except socket.error:
        print 'Please use a valid IP syntax: {}' .format(host_name_and_port[0])
        sys.exit(1)

    return host_name_and_port[0], int(host_name_and_port[1])
Exemplo n.º 6
0
    def _write_SOCKS5_address(self, addr, file):
        """
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        """
        host, port = addr
        proxy_type, _, _, rdns, username, password = self.proxy

        # If the given destination address is an IP address, we'll
        # use the IPv4 address request even if remote resolving was specified.
        try:
            addr_bytes = socket.inet_aton(host)
            file.write(b"\x01" + addr_bytes)
            host = socket.inet_ntoa(addr_bytes)
        except socket.error:
            # Well it's not an IP number, so it's probably a DNS name.
            if rdns:
                # Resolve remotely
                host_bytes = host.encode('idna')
                file.write(
                    b"\x03" + chr(len(host_bytes)).encode() + host_bytes)
            else:
                # Resolve locally
                addr_bytes = socket.inet_aton(socket.gethostbyname(host))
                file.write(b"\x01" + addr_bytes)
                host = socket.inet_ntoa(addr_bytes)

        file.write(struct.pack(">H", port))
        return host, port
Exemplo n.º 7
0
Arquivo: args.py Projeto: FI-Lab/ovs
def ip_address(string):
    """Verifies if string is a valid IP address"""
    try:
        socket.inet_aton(string)
    except socket.error:
        raise argparse.ArgumentTypeError("Not a valid IPv4 address")
    return string
Exemplo n.º 8
0
    def get_all_names(self):
        """Returns all names found in the Nginx Configuration.

        :returns: All ServerNames, ServerAliases, and reverse DNS entries for
                  virtual host addresses
        :rtype: set

        """
        all_names = set()

        for vhost in self.parser.get_vhosts():
            all_names.update(vhost.names)

            for addr in vhost.addrs:
                host = addr.get_addr()
                if common.hostname_regex.match(host):
                    # If it's a hostname, add it to the names.
                    all_names.add(host)
                elif not common.private_ips_regex.match(host):
                    # If it isn't a private IP, do a reverse DNS lookup
                    # TODO: IPv6 support
                    try:
                        socket.inet_aton(host)
                        all_names.add(socket.gethostbyaddr(host)[0])
                    except (socket.error, socket.herror, socket.timeout):
                        continue

        return util.get_filtered_names(all_names)
Exemplo n.º 9
0
def is_ip(address):
    try:
        socket.inet_aton(address)
        ip = True
    except socket.error:
        ip = False
    return ip
Exemplo n.º 10
0
def inet_pton(family, addr):
    if family == socket.AF_INET:
        return socket.inet_aton(addr)
    elif family == socket.AF_INET6:
        if '.' in addr:  # a v4 addr
            v4addr = addr[addr.rindex(':') + 1:]
            v4addr = socket.inet_aton(v4addr)
            v4addr = map(lambda x: ('%02X' % ord(x)), v4addr)
            v4addr.insert(2, ':')
            newaddr = addr[:addr.rindex(':') + 1] + ''.join(v4addr)
            return inet_pton(family, newaddr)
        dbyts = [0] * 8  # 8 groups
        grps = addr.split(':')
        for i, v in enumerate(grps):
            if v:
                dbyts[i] = int(v, 16)
            else:
                for j, w in enumerate(grps[::-1]):
                    if w:
                        dbyts[7 - j] = int(w, 16)
                    else:
                        break
                break
        return ''.join((chr(i // 256) + chr(i % 256)) for i in dbyts)
    else:
        raise RuntimeError("What family?")
Exemplo n.º 11
0
 def valid_ipv4(self):
     try:
         socket.inet_aton(self.host)
         return True
     except:
         print "The format of hostip is not correctly"
         return False
Exemplo n.º 12
0
def incrementclientip():
    netparts = []
    iplist = []
    startip = 2
    
    #p = subprocess.Popen(['/usr/local/openvpn_as/scripts/confdba', '-s'], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    #tmpdba, err = p.communicate()
    #confdba = ast.literal_eval(tmpdba)
    
    p = subprocess.Popen(['cat', '/root/bin/confdbas.txt'], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    tmpdba, err = p.communicate()
    confdba = ast.literal_eval(tmpdba)
    
    for key1,val1 in confdba.items():
        if key1 == 'Default':
            if isinstance(val1, dict):
                for key2,val2 in val1.items():
                    if key2 == 'vpn.server.static.0.network':
                        network = val1.get('vpn.server.static.0.network', None)
                        netmask = val1.get('vpn.server.static.0.netmask_bits', None)
                        
    startipdec = ip2int(network)                        #decimal form of the network address
    maxclients = pow(2,(32 - int(netmask))) - startip   #decimal form of the number of hosts with given mask
    print maxclients
    minipdec = startipdec + startip + 8192                        #lowest ip in decimal format
    maxipdec = startipdec + maxclients + startip - 2 + 8192      #highest ip in decimal format
    minip = int2ip(minipdec)                                #lowest ip in dotted notation
    maxip = int2ip(maxipdec)                                #highest ip in dotted notation

    #p = subprocess.Popen(['/usr/local/openvpn_as/scripts/confdba', '-us'], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    #tmpdba, err = p.communicate()
    #userdba = ast.literal_eval(tmpdba)

    p = subprocess.Popen(['cat', '/root/bin/confdbaus.txt'], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    tmpdba, err = p.communicate()
    userdba = ast.literal_eval(tmpdba)

    for key1,val1 in userdba.items():
        if isinstance(val1, dict):
            for key2,val2 in val1.items():
                usertype = val1.get(key2, val2)
                if usertype == 'user_connect' or usertype == 'user_compile':
                    userip = val1.get('conn_ip', None)
                    if userip:
                        try:
                            socket.inet_aton(userip)  #Makes sure the groups are in IPv4 network form for sorted below
                            iplist.append(userip)
                        except:
                            pass
    
    for seqdec in range(minipdec, maxipdec):
        seqip = int2ip(seqdec)
        if checkip(seqip, iplist):
            pass
        else:
            newclientip = seqip
            break
    
    print newclientip
    return newclientip
 def arp_spoof(self, ip_poison, ip_victims=[], local_mac=None, interface="wlan0"):
     if ip_poison:
         sock_arp_spoof = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.ntohs(0x0806))
         sock_arp_spoof.bind((interface, socket.htons(0x0806)))
         if local_mac:
             mac_source = local_mac
         else: mac_source = self.get_local_mac_address()
         
         code ='\x08\x06'
         htype = '\x00\x01'
         protype = '\x08\x00'
         hsize = '\x06'
         psize = '\x04'
         opcode = '\x00\x02'
         ip_poison_formated = socket.inet_aton(ip_poison)
         if ip_victims:
             mac_victims = self.get_mac_address(ip_victims)
             arp_victims = {}
             for ip_address in mac_victims:
                 ip_address_formated = socket.inet_aton(ip_address)
                 eth = mac_victims[ip_address] + mac_source + code
                 arp_victim = eth + htype + protype + hsize + psize + opcode + mac_source + ip_poison_formated + mac_victims[ip_address] + ip_address_formated
                 arp_victims[ip_address] = arp_victim                 
         else:
             pass #send all ip network Ex:192.168.1.0  mac_dest = '\xFF\xFF\xFF\xFF\xFF\xFF'          
     
         while True:
             for arp_victim in arp_victims: 
                 sock_arp_spoof.send(arp_victim)  
Exemplo n.º 14
0
def build_ip_header(datalength, srcIP, dstIP):
    version = 4 # 4 bits
    headerlen = 5 # 5*32bits = 20 bytes # 4 bits
    dscp = 0 # 6 bits
    ecn = 0 # disable capability # 2 bits
    totalLength = datalength + 20 # 16 bits
    identification = 22641 # random # 16 bits
    flags = 0 # 3 bits
    fragmentOffset = 0 # 13 bits
    ttl = 64 # 8 bits
    proto = 6 # 8 bits
    chksum = 0 # initial value # 16 bits
    srcIP = socket.inet_aton(srcIP) # 32 bits
    dstIP = socket.inet_aton(dstIP) # 32 bits

    # Convert fields to binary
    version_headerlen = chr(((version & 0xf) << 4) | headerlen & 0x0f)
    dscp_ecn = "\0"
    totalLen = struct.pack("!H", totalLength)
    ident = "xD"
    flags_fragmentOffset = "\0\0"
    ttl = chr(64)
    proto = chr(6)
    chksum = "\0\0"

    without_checksum = version_headerlen + dscp_ecn + totalLen + ident + flags_fragmentOffset + ttl + proto + chksum + srcIP + dstIP
    chksum = checksum(without_checksum)
    if chksum == 0:
        chksum = 0xffff
    return without_checksum[:10] + chr(chksum >> 8) + chr(chksum & 0xff) + without_checksum[12:]
Exemplo n.º 15
0
 def __init__(self, dp, sp, da, sa):
     super(GPRSActionPushUDPIP,self).__init__(0x0003)
     self.len = 24
     self.sp = sp
     self.dp = dp
     self.da = socket.inet_aton(da)
     self.sa = socket.inet_aton(sa)
Exemplo n.º 16
0
    def __init__(self, addr, listen = "0.0.0.0"):
        '''
        Constructor
        '''
        threading.Thread.__init__(self)
        self.listen = listen
        self.daemon = True
        
        # Create the socket
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Set some options to make it multicast-friendly
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        except AttributeError:
            pass # Some systems don't support SO_REUSEPORT
        s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 20)
        s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)

        # Bind to the port
        s.bind(('', addr[1]))

        # Set some more multicast options
        s.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(self.listen))
        s.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(addr[0]) + socket.inet_aton(self.listen))

        self.sock = s
        self.addr = addr
        self.running = True
Exemplo n.º 17
0
def GetNetworkInterfaces():
    interfaces = list()
    try:
        objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
        objSWbemServices = objWMIService.ConnectServer(".", "root\cimv2")
        adapters = objSWbemServices.ExecQuery(
            "SELECT * FROM Win32_NetworkAdapterConfiguration")
        for adapter in adapters:
            if adapter.IPEnabled:
                inet = []
                inet6 = []
                if adapter.IPAddress:
                    for ip in adapter.IPAddress:
                        try:
                            socket.inet_aton(ip)
                            inet.append(ip)
                        except socket.error:
                            # Assume IPv6 if parsing as IPv4 was failed.
                            inet6.append(ip)
                interfaces.append({
                    'name': adapter.Description,
                    'inet': inet,
                    'inet6': inet6,
                    'hw': adapter.MacAddress.lower().replace('-', ':')})
    except:
        logging.exception("Error retrieving network interfaces.")
    return merge_duplicate_interfaces(interfaces)
Exemplo n.º 18
0
def create_udp_socket(mcast_addr, mcast_port):
    """Create an udp multicast socket for circusd cluster auto-discovery.
    mcast_addr must be between 224.0.0.0 and 239.255.255.255
    """
    try:
        ip_splitted = list(map(int, mcast_addr.split('.')))
        mcast_port = int(mcast_port)
    except ValueError:
        raise ValueError('Wrong UDP multicast_endpoint configuration. Should '
                         'looks like: "%r"' % DEFAULT_ENDPOINT_MULTICAST)

    if ip_splitted[0] < 224 or ip_splitted[0] > 239:
        raise ValueError('The multicast address is not valid should be '
                         'between 224.0.0.0 and 239.255.255.255')

    any_addr = "0.0.0.0"
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    # Allow reutilization of addr
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Some platform exposes SO_REUSEPORT
    if hasattr(socket, 'SO_REUSEPORT'):
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        except socket.error:
            # see #699
            pass
    # Put packet ttl to max
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255)
    # Register socket to multicast group
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                    socket.inet_aton(mcast_addr) + socket.inet_aton(any_addr))
    # And finally bind all interfaces
    sock.bind((any_addr, mcast_port))
    return sock
Exemplo n.º 19
0
    def tcp_header(self, data='', syn=False, ack=False, psh = False, fin = False):
        # tcp header
        tcp_doff = 5    
        #tcp flags
        tcp_fin = int(fin)
        tcp_syn = int(syn)
        tcp_rst = 0
        tcp_psh = int(psh)
        tcp_ack = int(ack)
        tcp_urg = 0
        tcp_window = socket.htons (2048)   
        tcp_check = 0
        tcp_urg_ptr = 0

        tcp_offset_res = (tcp_doff << 4) + 0
        tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5)

        tcp_header = pack('!HHLLBBHHH' , self.src_port, self.dst_port, self.tcp_seq, self.tcp_ack_seq, tcp_offset_res, tcp_flags,  tcp_window, tcp_check, tcp_urg_ptr)

        source_address = socket.inet_aton( self.src_ip )
        dest_address = socket.inet_aton(self.dst_ip)
        placeholder = 0
        protocol = socket.IPPROTO_TCP
        tcp_length = len(tcp_header) + len(data)

        psh = pack('!4s4sBBH' , source_address , dest_address , placeholder , protocol , tcp_length);
        psh = psh + tcp_header + data;

        tcp_check = self.checksum(psh)

        return pack('!HHLLBBH' , self.src_port, self.dst_port, self.tcp_seq, self.tcp_ack_seq, tcp_offset_res, tcp_flags,  tcp_window) + pack('H' , tcp_check) + pack('!H' , tcp_urg_ptr)
Exemplo n.º 20
0
def _parse_options(options):
	packet = ''
	for option in options:
		code, value = option

		# with single byte value
		if code in [__OPTION_MESSAGE_TYPE__]:
			packet += (struct.pack("!3B", code ,1,value))
			continue

		# with single ip address as value
		if code in [__OPTION_NETMASK__, __OPTION_BROADCAST_ADDRESS__, __OPTION_SERVER_IDENTIFIER__,__OPTION_REQUESTED_ADDRESS__]:
			packet += (struct.pack("!2B", code, 4)+socket.inet_aton(value))
			continue
			
		# with multiple ip address as value
		if code in [__OPTION_ROUTERS__, __OPTION_NTP_SERVERS__, __OPTION_DNS_SERVERS__]:
			if len(value) == 0: continue # continue if no ip specified
			packet += (struct.pack("!2B", code, 4*len(value)))
			for address in value:
				packet += socket.inet_aton(address)
			continue

		# time relevent
		if code in [__OPTION_LEASE_TIME__, __OPTION_RENEW_TIME__, __OPTION_REBIND_TIME__]:
			packet += struct.pack("!2BI", code, 4, value)
			continue

		# other options, for now just concat them to the packet
		# developer should take care of the null character in the end
		packet += (struct.pack("!2B", code, len(value))+value)

	return packet
Exemplo n.º 21
0
def is_ip(value):
    """Determine if the given string is an IP address.

    Python 2 on Windows doesn't provide ``inet_pton``, so this only
    checks IPv4 addresses in that environment.

    :param value: value to check
    :type value: str

    :return: True if string is an IP address
    :rtype: bool
    """
    if PY2 and os.name == 'nt':
        try:
            socket.inet_aton(value)
            return True
        except socket.error:
            return False

    for family in (socket.AF_INET, socket.AF_INET6):
        try:
            socket.inet_pton(family, value)
        except socket.error:
            pass
        else:
            return True

    return False
Exemplo n.º 22
0
    def _verify_path_your_ip_args(self, fields):
        """Verify /your_ip request's arguments

        Make sure that the POST arguments send by the client while requesting
        for /your_ip path are valid.

        Args:
            fields: decoded POST arguments sent by the client in the form of
                    dictionary

        Raises:
            RequestProcessingException: some/all arguments are missing and/or
                                        malformed. Request should be aborted.
        """
        if "reflector_ip" not in fields or "reflector_port" not in fields:
            raise RequestProcessingException(400, 'Reflector data missing',
                                             'Reflector IP and/or port has not '
                                             'been provided, so the request cannot '
                                             'be processed.')

        fields['reflector_ip'] = fields['reflector_ip'][0]
        fields['reflector_port'] = fields['reflector_port'][0]

        try:
            fields['reflector_port'] = int(fields['reflector_port'])
        except ValueError:
            msg = 'Reflector port "{}" is not an integer'
            raise RequestProcessingException(400, msg.format(fields['reflector_port']))

        try:
            socket.inet_aton(fields['reflector_ip'])
        except socket.error:
            msg = 'Reflector IP "{}" is invalid/not a proper ipv4'
            raise RequestProcessingException(400, msg.format(fields['reflector_ip']))
Exemplo n.º 23
0
    def __init__(self, address=None, netmask=None, nameservers=None, gateway=None, domain=None, globals=None, entries=None):
        self.domain = domain
        self.address = inet_aton(address)
        self.netmask = inet_aton(netmask)

        self.broadcast = bytes([(a | ~b & 255) for (a, b) in zip(self.address, self.netmask)])

        if nameservers:
            self.resolvers = bytearray()
            for ns in nameservers:
                self.resolvers.extend(inet_aton(ns))
        else:
            self.resolvers = None

        if gateway:
            self.gateway = inet_aton(gateway)
        else:
            self.gateway = None

        self.leases = {}
        self.offers = {}

        self.globals = globals if globals else {}
        self.entries = entries if entries else {}

        self.reserved = {}
        for (k, v) in self.entries.items():
            addr = v.get('address')
            if addr:
                self.reserved[inet_aton(addr)] = True
Exemplo n.º 24
0
def registerActuator():
    global acuator_registry
    try:
        request_data = request.json
    except ValueError:
        return HTTPResponse(status=400, body="Request body must be valid JSON")

    if request_data is None:
        return HTTPResponse(status=400, body="Request body must be valid JSON")

    ip_addr = request_data.get("IP")
    if ip_addr is None:
        return HTTPResponse(status=400, body="Request body must contain IP address")
    try:
        socket.inet_aton(ip_addr) # Quick & dirty way to validate an IP address
    except socket.error:
        return HTTPResponse(status=400, body="Improperly formatted IP address")
    name = request_data.get("Name")
    if name is None:
        return HTTPReponse(status=400, body="Request body must contain name")

    actuator_registry[name] = ip_addr
    header = {"Content-Type" : "application/json"}
    timestamp = getCurrentTime()
    return HTTPResponse(status=201, body=json.dumps(timestamp), headers=header)
Exemplo n.º 25
0
def outgoing_packet_handler(src_port, dst_addr, dst_port, data):
	udp_frag = udp.Packet(sport=src_port, dport=dst_port, data=data)
	udp_assembled = udp.assemble(udp_frag, False)
	pseudo_header = socket.inet_aton(local_ip) + socket.inet_aton(dst_addr) + '\x00\x11' + struct.pack('!H', len(udp_assembled))
	cksum = inetutils.cksum(pseudo_header + udp_assembled)
	udp_assembled_with_cksum = udp_assembled[:6] + struct.pack('H', cksum) + udp_assembled[8:]
	out_sk.sendto(udp_assembled_with_cksum, (dst_addr, 0))
Exemplo n.º 26
0
def getNetworkAddr():
	ip = getIP()
	netmark = getNetmark()
	ipBit = unpack( 'L', inet_aton( ip ) )[0]
	netmarkBit = unpack( 'L', inet_aton( netmark ) )[0]
	
	return inet_ntoa( pack( 'L', ipBit & netmarkBit ) )
Exemplo n.º 27
0
    def send(self, data, dest=None):
        """Sends over UDP socket, if no destination address is found,
           multicast address is used"""

        if dest == None and self.__dest == None and self.__intfs != None:
            dest = (MCAST_ADDR, PORT)

            if len(self.__intfs) > 0:
                for intf in self.__intfs:
                    self.__sock.setsockopt(socket.SOL_IP, 
                        socket.IP_MULTICAST_IF, socket.inet_aton(intf))
                    self.__sock.sendto(data, dest)
            else:
                # let OS determine default interface
                self.__sock.sendto(data, dest)
                # hack for socialvpn
                try:
                    self.__sock.setsockopt(socket.SOL_IP, 
                        socket.IP_MULTICAST_IF, socket.inet_aton('172.31.0.2'))
                    self.__sock.sendto(data, dest)
                except Exception as ex:
                    logging.exception(ex)

        elif dest == None and self.__dest != None:
            dest = self.__dest
            self.__sock.sendto(data, dest)

        elif dest != None:
            self.__sock.sendto(data, dest)

        logging.debug('UDP send : %s : %s' % (dest, data))
        return dest
Exemplo n.º 28
0
def addressInNetwork(ip,net):
   """ Check if IpParam is an address in a network (works for ipv6 ::1)"""

   ipaddr = struct.unpack('I',socket.inet_aton(ip))[0]
   netaddr,bits = net.split('/')
   netmask = struct.unpack('I',socket.inet_aton(netaddr))[0] & ((2L<<int(bits)-1) - 1)
   return ipaddr & netmask == netmask
Exemplo n.º 29
0
    def record_parse(self, item):
        record = {
            'src_addr':   {'format': '!I', 'offset': 0, 'value': 0},
            'dst_addr':   {'format': '!I', 'offset': 4, 'value': 0},
            'next_hop':   {'format': '!I', 'offset': 8, 'value': 0},
            'input_idx':  {'format': '!H', 'offset': 12, 'value': 0},
            'output_idx': {'format': '!H', 'offset': 14, 'value': 0},
            'pkts':       {'format': '!I', 'offset': 16, 'value': 0},
            'octets':     {'format': '!I', 'offset': 20, 'value': 0},
            'first_time': {'format': '!I', 'offset': 24, 'value': 0},
            'last_time':  {'format': '!I', 'offset': 28, 'value': 0},
            'src_port':   {'format': '!H', 'offset': 32, 'value': 0},
            'dst_port':   {'format': '!H', 'offset': 34, 'value': 0},
            'pad1':       {'format': 'B',  'offset': 36, 'value': 0},
            'tcp_flags':  {'format': 'B',  'offset': 37, 'value': 0},
            'protocol':   {'format': 'B',  'offset': 38, 'value': 0},
            'tos':        {'format': 'B',  'offset': 39, 'value': 0},
            'src_as':     {'format': '!H', 'offset': 40, 'value': 0},
            'dst_as':     {'format': '!H', 'offset': 42, 'value': 0},
            'src_mask':   {'format': 'B',  'offset': 44, 'value': 0},
            'dst_mask':   {'format': 'B',  'offset': 45, 'value': 0},
            'pad2':       {'format': '!H', 'offset': 46, 'value': 0}
        }
        record['protocol']['value'] = item['protocol']
        record['src_addr']['value'] = struct.unpack('!I',
                socket.inet_aton(item['sourceip']))[0]
        record['dst_addr']['value'] = struct.unpack('!I',
                socket.inet_aton(item['destip']))[0]
        record['src_port']['value'] = item['sport']
        record['dst_port']['value'] = item['dport']

        # Parse record from FlowRecordTable
        #record['pkts']['value'] = item['agg-packets']
        #record['octets']['value'] = item['agg-bytes']
        #record['first_time']['value'] = (
        #        int(item['setup_time'] / 1000) - self.boot_time_ms)
        #if record['first_time']['value'] < 0:
        #    record['first_time']['value'] = 0
        #if item['teardown_time'] > 0:
        #    record['last_time']['value'] = (
        #            int(item['teardown_time'] / 1000) - self.boot_time_ms)
        #    if record['last_time']['value'] < 0:
        #        record['last_time']['value'] = 0

        # Parse record from FlowSeriesTable
        record['pkts']['value'] = item['packets']
        record['octets']['value'] = item['bytes']
        record['first_time']['value'] = (
                int(item['T'] / 1000) - self.boot_time_ms)
        if record['first_time']['value'] < 0:
            record['first_time']['value'] = 0
        # Fake last time.
        record['last_time']['value'] = record['first_time']['value'] + \
                random.randint(1, 100)

        self.record_list.append(record)
        self.record_count += 1

        if (self.record_count == 30):
            self.record_send()
Exemplo n.º 30
0
    def edit_ip_address(self, controlID):
        relevant_label_control = self.getControl(900000 + controlID)
        current_label = relevant_label_control.getLabel()

        if current_label == '___ : ___ : ___ : ___':
            current_label = ''

        user_input = DIALOG.input(lang(32004), current_label, type=xbmcgui.INPUT_IPADDRESS)

        if not user_input or user_input == '0.0.0.0':

            relevant_label_control.setLabel(current_label)

        else:
            # validate ip_address format
            try:
                socket.inet_aton(user_input)

            except:
                'The address provided is not a valid IP address.', 'OSMC Network Setup'
                ok = DIALOG.ok(lang(32004), lang(32005))

                self.edit_ip_address(controlID)

                return

            # ip_string = ' : '.join(str(user_input).split('.'))
            relevant_label_control.setLabel(user_input)

            return
Exemplo n.º 31
0
def ip2long(ip):
    return struct.unpack("!I",socket.inet_aton(ip))[0]
Exemplo n.º 32
0
     log.info('Reading addresses from {}'.format(args.addresses))
     with File2(args.addresses) as f:
         addresses.update(l.strip() for l in f)
 neighbors = defaultdict(list)
 for x, y in adjacencies:
     neighbors[(x, True)].append(y)
     neighbors[(y, False)].append(x)
 if args.interfaces:
     df = pd.read_csv(args.interfaces, index_col='Address', delimiter=',')
     asns = df['ASN'].to_dict()
     orgs = df['Org'].to_dict()
     othersides = df['Otherside'].to_dict()
     # asns, orgs, othersides = df['ASN', 'Org', 'Otherside'].to_dict('records')
 else:
     addresses = {
         struct.unpack("!L", socket.inet_aton(addr.strip()))[0]
         for addr in addresses
         if (':' not in addr or args.addr_family == "IPv6")
     }
     ip2as = create_routing_table(args.bgp,
                                  args.ixp_prefixes,
                                  args.ixp_asns,
                                  bgp_compression=args.bgp_compression)
     as2org = AS2Org(args.as2org, include_potaroo=args.potaroo)
     status('Extracting addresses from adjacencies')
     unique_interfaces = {u
                          for u, _ in adjacencies
                          } | {v
                               for _, v in adjacencies}
     finish_status('Found {:,d}'.format(len(unique_interfaces)))
     log.info('Mapping IP addresses to ASes.')
Exemplo n.º 33
0
def parse_dns_response(ip_packet, ts):
    # Check if it is in the allowed or banned IP lists
    clientIP = socket.inet_ntoa(ip_packet.dst)
    cip_object = ipaddress.ip_network(clientIP)
    allowed = False
    for ip in allowed_ips:
        if is_subnet_of(cip_object, ip):
            allowed = True
            break

    if (not allowed):
        return

    for ip in banned_ips:
        if is_subnet_of(cip_object, ip):
            return


    try:
        dns = dpkt.dns.DNS(ip_packet.data.data)
    except:
        return
    answers = dns.an

    if len(answers) <= 0:
        return
    domain = answers[0].name
    domain_name = domain.split('.')

    # Parser limitations
    if (len(domain_name) > 4):
        return
    for part in domain_name:
        if (len(part) > 15):
            return

    for d in known_domains:
        if (matchDomain(d, domain)):
            
            for rr in answers:
                if (rr.type != 1):
                    continue
                if (rr.type == 1): #DNS.A
                    entry = unlimitedKnownDict[d]
                    unlimitedKnownDict[d][0] = unlimitedKnownDict[d][0] + 1
                    
                    serverIP = socket.inet_ntoa(rr.rdata)

                    key = clientIP + serverIP

                    unlimitedNetTable[key] = d
                    break
            break

    for g in [1, 2, 4, 8]:
        for q in range(0, 34, 2):

            modulo = int((2 ** q) / g)

            for d in known_domains:
                if (matchDomain(d, domain)):

                    for rr in answers:
                        if (rr.type != 1):
                            continue
                        if (rr.type == 1): #DNS.A
                            entry = knownlistDicts_stages[g][q][d]
                            knownlistDicts_stages[g][q][d][0] = knownlistDicts_stages[g][q][d][0] + 1
                            
                            serverIP = socket.inet_ntoa(rr.rdata)
                            serverIP32 = np.uint64(int.from_bytes(socket.inet_aton(serverIP), byteorder='big'))
                            clientIP32 = np.uint64(int.from_bytes(socket.inet_aton(clientIP), byteorder='big'))
                            #serverIP32 = int.from_bytes(socket.inet_aton(serverIP), byteorder='big')
                            #clientIP32 = int.from_bytes(socket.inet_aton(clientIP), byteorder='big')

                            salts = [np.uint64(134140211), np.uint64(187182238), np.uint64(187238), np.uint64(1853238), np.uint64(1828), np.uint64(12238), np.uint64(72134), np.uint64(152428), np.uint64(164314534), np.uint64(223823)]
                            key = clientIP + serverIP

                            for z in range(0, 8):

                                if modulo > 0:
                                    hashz = (zlib.crc32(np.uint64(serverIP32 + clientIP32 + salts[z]))& 0xffffffff) % modulo
                                    #hashz = hash_function(serverIP32, clientIP32, salts[z]) % modulo
                                else:
                                    hashz = 0

                                if(not hashz in usedHashes[g][q][z]):
                                    usedHashes[g][q][z][hashz] = [ts, key, domain]
                                elif (ts - usedHashes[g][q][z][hashz][0] > TIMEOUT): # timestamp expires
                                    netassayTables_stages[g][q][z].pop(usedHashes[g][q][z][hashz][1])
                                    usedHashes[g][q][z][hashz] = [ts, key, domain]
                                elif(usedHashes[g][q][z][hashz][1] == key): # update timestamp for existing entry
                                    usedHashes[g][q][z][hashz] = [ts, key, domain]
                                elif(g < z + 2):
                                    knownlistDicts_stages[g][q][d][3] = knownlistDicts_stages[g][q][d][3]+1
                                    break
                                else:
                                    continue

                                netassayTables_stages[g][q][z][key] = d
                                break
                            break
                    break
Exemplo n.º 34
0
def valid_ip(address):
    try:
        socket.inet_aton(address)
        return True
    except socket.error:
        return False
Exemplo n.º 35
0
    def prepare_udp(self):
        self._prepare_socket()
        try:
            self.udpsock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            self.udpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

            #  On some platforms we have to ask to reuse the port
            try:
                self.udpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT,
                                        1)

            except AttributeError:
                pass

            if self.broadcast_address.is_multicast:
                # TTL
                self.udpsock.setsockopt(socket.IPPROTO_IP,
                                        socket.IP_MULTICAST_TTL, 2)

                # TODO: This should only be used if we do not have inproc method!
                self.udpsock.setsockopt(socket.IPPROTO_IP,
                                        socket.IP_MULTICAST_LOOP, 1)

                # Usually, the system administrator specifies the
                # default interface multicast datagrams should be
                # sent from. The programmer can override this and
                # choose a concrete outgoing interface for a given
                # socket with this option.
                #
                # this results in the loopback address?
                # host = socket.gethostbyname(socket.gethostname())
                # self.udpsock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))
                # You need to tell the kernel which multicast groups
                # you are interested in. If no process is interested
                # in a group, packets destined to it that arrive to
                # the host are discarded.
                # You can always fill this last member with the
                # wildcard address (INADDR_ANY) and then the kernel
                # will deal with the task of choosing the interface.
                #
                # Maximum memberships: /proc/sys/net/ipv4/igmp_max_memberships
                # self.udpsock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP,
                #       socket.inet_aton("225.25.25.25") + socket.inet_aton(host))
                self.udpsock.bind(("", self.port_nbr))

                group = socket.inet_aton("{0}".format(self.broadcast_address))
                mreq = struct.pack('4sl', group, socket.INADDR_ANY)

                self.udpsock.setsockopt(socket.SOL_IP,
                                        socket.IP_ADD_MEMBERSHIP, mreq)

            else:
                # Platform specifics
                if sys.platform.startswith("linux"):
                    # on linux we bind to the broadcast address and send to
                    # the broadcast address
                    self.udpsock.bind(
                        (str(self.broadcast_address), self.port_nbr))
                else:
                    self.udpsock.bind(("", self.port_nbr))

                logger.debug("Set up a broadcast beacon to {0}:{1}".format(
                    self.broadcast_address, self.port_nbr))
        except socket.error:
            logger.exception("Initializing of {0} raised an exception".format(
                self.__class__.__name__))
Exemplo n.º 36
0
def valid_ip(ip):
    try:
        socket.inet_aton(ip)
    except socket.error:
        return False
    return True
Exemplo n.º 37
0
def addr_to_bytes(addr):
    return inet_aton(addr[0]) + addr[1].to_bytes(4, 'big')
Exemplo n.º 38
0
import socket
import struct

source_ip = '192.168.1.101'
dest_ip = '192.168.1.1'  # or socket.gethostbyname('www.google.com')

# ip header fields
ip_ihl = 5
ip_ver = 4
ip_tos = 0
ip_tot_len = 0  # kernel will fill the correct total length
ip_id = 54321  # Id of this packet
ip_frag_off = 0
ip_ttl = 255
ip_proto = socket.IPPROTO_TCP
ip_check = 0  # kernel will fill the correct checksum
ip_saddr = socket.inet_aton(
    source_ip)  # Spoof the source ip address if you want to
ip_daddr = socket.inet_aton(dest_ip)

ip_ihl_ver = (version << 4) + ihl

# the ! in the pack format string means network order
ip_header = struct.pack('!BBHHHBBH4s4s', ip_ihl_ver, ip_tos, ip_tot_len, ip_id,
                        ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr,
                        ip_daddr)
Exemplo n.º 39
0
 def get_packed_address(self, address):
     packed_ip = socket.inet_aton(address.host)
     packed_port = struct.pack('>H', address.port)
     return packed_ip, packed_port
Exemplo n.º 40
0
def is_ipv4(addr):
    try:
        socket.inet_aton(addr)
        return True
    except socket.error:
        return False
 def inet_pton(_, host):
     return socket.inet_aton(host)
Exemplo n.º 42
0
    def craft_options(self, opt53, client_mac):
        '''
            @brief This method crafts the DHCP option fields
            @param opt53:
            *    2 - DHCPOFFER
            *    5 - DHCPACK
            @see RFC2132 9.6 for details.
        '''
        response = self.tlv_encode(53, chr(opt53))  # message type, OFFER
        response += self.tlv_encode(54,
                                    socket.inet_aton(self.ip))  # DHCP Server
        if not self.mode_proxy:
            subnet_mask = self.get_namespaced_static(
                'dhcp.binding.{0}.subnet'.format(self.get_mac(client_mac)),
                self.subnet_mask)
            response += self.tlv_encode(
                1, socket.inet_aton(subnet_mask))  # subnet mask
            router = self.get_namespaced_static(
                'dhcp.binding.{0}.router'.format(self.get_mac(client_mac)),
                self.router)
            response += self.tlv_encode(3, socket.inet_aton(router))  # router
            dns_server = self.get_namespaced_static(
                'dhcp.binding.{0}.dns'.format(self.get_mac(client_mac)),
                [self.dns_server])
            dns_server = ''.join([socket.inet_aton(i) for i in dns_server])
            response += self.tlv_encode(6, dns_server)
            response += self.tlv_encode(51, struct.pack('!I',
                                                        86400))  # lease time

        # TFTP Server OR HTTP Server; if iPXE, need both
        response += self.tlv_encode(66, self.file_server)

        # file_name null terminated
        if not self.ipxe or not self.leases[client_mac]['ipxe']:
            # http://www.syslinux.org/wiki/index.php/PXELINUX#UEFI
            if 93 in self.leases[client_mac][
                    'options'] and not self.force_file_name:
                [arch
                 ] = struct.unpack("!H",
                                   self.leases[client_mac]['options'][93][0])
                if arch == 0:  # BIOS/default
                    response += self.tlv_encode(67, 'pxelinux.0' + chr(0))
                elif arch == 6:  # EFI IA32
                    response += self.tlv_encode(67, 'syslinux.efi32' + chr(0))
                elif arch == 7:  # EFI BC, x86-64 (according to the above link)
                    response += self.tlv_encode(67, 'syslinux.efi64' + chr(0))
                elif arch == 9:  # EFI x86-64
                    response += self.tlv_encode(67, 'syslinux.efi64' + chr(0))
            else:
                response += self.tlv_encode(67, self.file_name + chr(0))
        else:
            response += self.tlv_encode(67, 'chainload.kpxe' +
                                        chr(0))  # chainload iPXE
            if opt53 == 5:  # ACK
                self.leases[client_mac]['ipxe'] = False
        if self.mode_proxy:
            response += self.tlv_encode(60, 'PXEClient')
            response += struct.pack('!BBBBBBB4sB', 43, 10, 6, 1, 0b1000, 10, 4,
                                    chr(0) + 'PXE', 0xff)
        response += '\xff'
        return response
Exemplo n.º 43
0
         networkdiscovery(options.network)
         sys.exit()        
 if len(args)<1 and options.iplist==None:
         parser.print_help()
         sys.exit()
 if options.noping== True and options.noscan == True:
         print 'ERROR: Cannot use -N and -P together'
         sys.exit()
 iplist=[]
 if options.iplist==None:
         ipaddr=args[0]
         if len(args)==2:
                 print 'Must specify end port'
                 sys.exit()
         try:
                 sk.inet_aton(ipaddr)
                 iplist.append(ipaddr)
         except:                
                 if not validateCIDRBlock(ipaddr):
                         print 'IP address not valid!'
                         sys.exit()
                 else:
                         iplist=listCIDR(ipaddr)
 else:
         iplist=parseIPlist(options.iplist)
 #print iplist        
 if options.iplist==None and len(args)==3:
         startport=int(args[1])
         endport=int(args[2])
         if startport>endport:
                 print 'start port must be smaller or equal to end port'
Exemplo n.º 44
0
#!usr/bin/env python3

import socket

while True:
    ipchk = input("Apply an IP address: ")

    if ipchk == "192.168.70.1":
        print("Looks like the IP address is set: " + ipchk + ".")
    elif ipchk:
        try:
            socket.inet_aton(ipchk)
            print("Looks like the IP address was set: " + ipchk)
            break
        except:
            print("That's not an IP Address, ya big dummy!")
    else:
        print("You did not provide any input.")

Exemplo n.º 45
0
def checksum(msg):
s = 0
# loop taking 2 characters at a time
for i in range(0, len(msg), 2):
w = (ord(msg[i]) << 8) + (ord(msg[i+1]) )         s = s + w           s = (s>>16) + (s & 0xffff);
#s = s + (s >> 16);
#complement and mask to 4 byte short
s = ~s & 0xffff

return s

#create a raw socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
except socket.error , msg:
print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()

# tell kernel not to put in headers, since we are providing it
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

# now start constructing the packet
packet = '';

source_ip = '192.168.1.101'
dest_ip = '192.168.1.1' # or socket.gethostbyname('www.google.com')

# ip header fields
ihl = 5
version = 4
tos = 0
tot_len = 20 + 20   # python seems to correctly fill the total length, dont know how ??
id = 54321  #Id of this packet
frag_off = 0
ttl = 255
protocol = socket.IPPROTO_TCP
check = 10  # python seems to correctly fill the checksum
saddr = socket.inet_aton ( source_ip )  #Spoof the source ip address if you want to
daddr = socket.inet_aton ( dest_ip )

ihl_version = (version << 4) + ihl

# the ! in the pack format string means network order
ip_header = pack('!BBHHHBBH4s4s' , ihl_version, tos, tot_len, id, frag_off, ttl, protocol, check, saddr, daddr)

# tcp header fields
source = 1234   # source port
dest = 80   # destination port
seq = 0
ack_seq = 0
doff = 5    #4 bit field, size of tcp header, 5 * 4 = 20 bytes
#tcp flags
fin = 0
syn = 1
rst = 0
psh = 0
ack = 0
urg = 0
window = socket.htons (5840)    #   maximum allowed window size
check = 0
urg_ptr = 0

offset_res = (doff << 4) + 0
tcp_flags = fin + (syn << 1) + (rst << 2) + (psh <<3) + (ack << 4) + (urg << 5)

# the ! in the pack format string means network order
tcp_header = pack('!HHLLBBHHH' , source, dest, seq, ack_seq, offset_res, tcp_flags,  window, check, urg_ptr)

# pseudo header fields
source_address = socket.inet_aton( source_ip )
dest_address = socket.inet_aton(dest_ip)
placeholder = 0
protocol = socket.IPPROTO_TCP
tcp_length = len(tcp_header)

psh = pack('!4s4sBBH' , source_address , dest_address , placeholder , protocol , tcp_length);
psh = psh + tcp_header;

tcp_checksum = checksum(psh)

# make the tcp header again and fill the correct checksum
tcp_header = pack('!HHLLBBHHH' , source, dest, seq, ack_seq, offset_res, tcp_flags,  window, tcp_checksum , urg_ptr)

# final full packet - syn packets dont have any data
packet = ip_header + tcp_header

#Send the packet finally - the port specified has no effect
s.sendto(packet, (dest_ip , 0 ))    # put this in a loop if you want to flood the target
Exemplo n.º 46
0
 def prefix_len(netmask):
     return bin(int(socket.inet_aton(netmask).encode('hex'),
                    16)).count('1')
Exemplo n.º 47
0
async def test_dbus_resolved_info(coresys_ip_bytes: CoreSys):
    """Test systemd-resolved dbus connection."""
    coresys = coresys_ip_bytes

    assert coresys.dbus.resolved.dns is None

    await coresys.dbus.resolved.connect()
    await coresys.dbus.resolved.update()

    assert coresys.dbus.resolved.llmnr_hostname == "homeassistant"
    assert coresys.dbus.resolved.llmnr == MulticastProtocolEnabled.YES
    assert coresys.dbus.resolved.multicast_dns == MulticastProtocolEnabled.RESOLVE
    assert coresys.dbus.resolved.dns_over_tls == DNSOverTLSEnabled.NO

    assert len(coresys.dbus.resolved.dns) == 2
    assert coresys.dbus.resolved.dns[0] == [0, 2, inet_aton("127.0.0.1")]
    assert coresys.dbus.resolved.dns[1] == [0, 10, inet_pton(AF_INET6, "::1")]
    assert len(coresys.dbus.resolved.dns_ex) == 2
    assert coresys.dbus.resolved.dns_ex[0] == [0, 2, inet_aton("127.0.0.1"), 0, ""]
    assert coresys.dbus.resolved.dns_ex[1] == [0, 10, inet_pton(AF_INET6, "::1"), 0, ""]

    assert len(coresys.dbus.resolved.fallback_dns) == 2
    assert coresys.dbus.resolved.fallback_dns[0] == [0, 2, inet_aton("1.1.1.1")]
    assert coresys.dbus.resolved.fallback_dns[1] == [
        0,
        10,
        inet_pton(AF_INET6, "2606:4700:4700::1111"),
    ]
    assert len(coresys.dbus.resolved.fallback_dns_ex) == 2
    assert coresys.dbus.resolved.fallback_dns_ex[0] == [
        0,
        2,
        inet_aton("1.1.1.1"),
        0,
        "cloudflare-dns.com",
    ]
    assert coresys.dbus.resolved.fallback_dns_ex[1] == [
        0,
        10,
        inet_pton(AF_INET6, "2606:4700:4700::1111"),
        0,
        "cloudflare-dns.com",
    ]

    assert coresys.dbus.resolved.current_dns_server == [0, 2, inet_aton("127.0.0.1")]
    assert coresys.dbus.resolved.current_dns_server_ex == [
        0,
        2,
        inet_aton("127.0.0.1"),
        0,
        "",
    ]

    assert len(coresys.dbus.resolved.domains) == 1
    assert coresys.dbus.resolved.domains[0] == [0, "local.hass.io", False]

    assert coresys.dbus.resolved.transaction_statistics == [0, 100000]
    assert coresys.dbus.resolved.cache_statistics == [10, 50000, 10000]
    assert coresys.dbus.resolved.dnssec == DNSSECValidation.NO
    assert coresys.dbus.resolved.dnssec_statistics == [0, 0, 0, 0]
    assert coresys.dbus.resolved.dnssec_supported is False
    assert coresys.dbus.resolved.dnssec_negative_trust_anchors == [
        "168.192.in-addr.arpa",
        "local",
    ]
    assert coresys.dbus.resolved.dns_stub_listener == DNSStubListenerEnabled.NO
    assert coresys.dbus.resolved.resolv_conf_mode == ResolvConfMode.FOREIGN
Exemplo n.º 48
0
def binary_ip(host):
    return inet_aton(gethostbyname(host))
import struct

multicast_group = '224.3.29.71'

frames = []
framesToSave = []

FORMAT = pyaudio.paInt16
CHUNK = 1024
CHANNELS = 2
RATE = 44100
WAVE_OUTPUT_FILENAME = "clientFile.wav"

p = pyaudio.PyAudio()

group = socket.inet_aton(multicast_group)
mreq = struct.pack('=4sL', group, socket.INADDR_ANY)

def udpStream():
	udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	udp.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
	while True:
		if len(frames) > 0:
			udp.sendto(frames.pop(0), ("127.0.0.1", 12344))
	udp.close()


def record(stream, CHUNK):
	while True:
		alpha = stream.read(CHUNK)
		# frames.append(alpha)
Exemplo n.º 50
0
def create_instances(module, gce, instance_names, number):
    """Creates new instances. Attributes other than instance_names are picked
    up from 'module'

    module : AnsibleModule object
    gce: authenticated GCE libcloud driver
    instance_names: python list of instance names to create

    Returns:
        A list of dictionaries with instance information
        about the instances that were launched.

    """
    image = module.params.get('image')
    machine_type = module.params.get('machine_type')
    metadata = module.params.get('metadata')
    network = module.params.get('network')
    subnetwork = module.params.get('subnetwork')
    persistent_boot_disk = module.params.get('persistent_boot_disk')
    disks = module.params.get('disks')
    state = module.params.get('state')
    tags = module.params.get('tags')
    zone = module.params.get('zone')
    ip_forward = module.params.get('ip_forward')
    external_ip = module.params.get('external_ip')
    disk_auto_delete = module.params.get('disk_auto_delete')
    preemptible = module.params.get('preemptible')
    disk_size = module.params.get('disk_size')
    service_account_permissions = module.params.get(
        'service_account_permissions')
    service_account_email = module.params.get('service_account_email')

    if external_ip == "none":
        instance_external_ip = None
    elif not isinstance(external_ip, basestring):
        try:
            if len(external_ip) != 0:
                instance_external_ip = external_ip.pop(0)
                # check if instance_external_ip is an ip or a name
                try:
                    socket.inet_aton(instance_external_ip)
                    instance_external_ip = GCEAddress(
                        id='unknown',
                        name='unknown',
                        address=instance_external_ip,
                        region='unknown',
                        driver=gce)
                except socket.error:
                    instance_external_ip = gce.ex_get_address(
                        instance_external_ip)
            else:
                instance_external_ip = 'ephemeral'
        except GoogleBaseError as e:
            module.fail_json(
                msg=
                'Unexpected error attempting to get a static ip %s, error: %s'
                % (external_ip, e.value))
    else:
        instance_external_ip = external_ip

    new_instances = []
    changed = False

    lc_disks = []
    disk_modes = []
    for i, disk in enumerate(disks or []):
        if isinstance(disk, dict):
            lc_disks.append(gce.ex_get_volume(disk['name']))
            disk_modes.append(disk['mode'])
        else:
            lc_disks.append(gce.ex_get_volume(disk))
            # boot disk is implicitly READ_WRITE
            disk_modes.append('READ_ONLY' if i > 0 else 'READ_WRITE')
    lc_network = gce.ex_get_network(network)
    lc_machine_type = gce.ex_get_size(machine_type)
    lc_zone = gce.ex_get_zone(zone)

    # Try to convert the user's metadata value into the format expected
    # by GCE.  First try to ensure user has proper quoting of a
    # dictionary-like syntax using 'literal_eval', then convert the python
    # dict into a python list of 'key' / 'value' dicts.  Should end up
    # with:
    # [ {'key': key1, 'value': value1}, {'key': key2, 'value': value2}, ...]
    if metadata:
        if isinstance(metadata, dict):
            md = metadata
        else:
            try:
                md = literal_eval(str(metadata))
                if not isinstance(md, dict):
                    raise ValueError('metadata must be a dict')
            except ValueError as e:
                module.fail_json(msg='bad metadata: %s' % str(e))
            except SyntaxError as e:
                module.fail_json(msg='bad metadata syntax')

        if hasattr(libcloud, '__version__') and libcloud.__version__ < '0.15':
            items = []
            for k, v in md.items():
                items.append({"key": k, "value": v})
            metadata = {'items': items}
        else:
            metadata = md

    lc_image = LazyDiskImage(module, gce, image, lc_disks)
    ex_sa_perms = []
    bad_perms = []
    if service_account_permissions:
        for perm in service_account_permissions:
            if perm not in gce.SA_SCOPES_MAP:
                bad_perms.append(perm)
        if len(bad_perms) > 0:
            module.fail_json(msg='bad permissions: %s' % str(bad_perms))
        ex_sa_perms.append({'email': "default"})
        ex_sa_perms[0]['scopes'] = service_account_permissions

    # These variables all have default values but check just in case
    if not lc_network or not lc_machine_type or not lc_zone:
        module.fail_json(msg='Missing required create instance variable',
                         changed=False)

    gce_args = dict(location=lc_zone,
                    ex_network=network,
                    ex_tags=tags,
                    ex_metadata=metadata,
                    ex_can_ip_forward=ip_forward,
                    external_ip=instance_external_ip,
                    ex_disk_auto_delete=disk_auto_delete,
                    ex_service_accounts=ex_sa_perms)
    if preemptible is not None:
        gce_args['ex_preemptible'] = preemptible
    if subnetwork is not None:
        gce_args['ex_subnetwork'] = subnetwork

    if isinstance(instance_names, str) and not number:
        instance_names = [instance_names]

    if isinstance(instance_names, str) and number:
        instance_responses = gce.ex_create_multiple_nodes(
            instance_names, lc_machine_type, lc_image(), number, **gce_args)
        for resp in instance_responses:
            n = resp
            if isinstance(resp, libcloud.compute.drivers.gce.GCEFailedNode):
                try:
                    n = gce.ex_get_node(n.name, lc_zone)
                except ResourceNotFoundError:
                    pass
            else:
                # Assure that at least one node has been created to set changed=True
                changed = True
            new_instances.append(n)
    else:
        for instance in instance_names:
            pd = None
            if lc_disks:
                pd = lc_disks[0]
            elif persistent_boot_disk:
                try:
                    pd = gce.ex_get_volume("%s" % instance, lc_zone)
                except ResourceNotFoundError:
                    pd = gce.create_volume(disk_size,
                                           "%s" % instance,
                                           image=lc_image())
            gce_args['ex_boot_disk'] = pd

            inst = None
            try:
                inst = gce.ex_get_node(instance, lc_zone)
            except ResourceNotFoundError:
                inst = gce.create_node(instance, lc_machine_type, lc_image(),
                                       **gce_args)
                changed = True
            except GoogleBaseError as e:
                module.fail_json(msg='Unexpected error attempting to create ' +
                                 'instance %s, error: %s' %
                                 (instance, e.value))
            if inst:
                new_instances.append(inst)

    for inst in new_instances:
        for i, lc_disk in enumerate(lc_disks):
            # Check whether the disk is already attached
            if (len(inst.extra['disks']) > i):
                attached_disk = inst.extra['disks'][i]
                if attached_disk['source'] != lc_disk.extra['selfLink']:
                    module.fail_json(msg=(
                        "Disk at index %d does not match: requested=%s found=%s"
                        % (i, lc_disk.extra['selfLink'],
                           attached_disk['source'])))
                elif attached_disk['mode'] != disk_modes[i]:
                    module.fail_json(msg=(
                        "Disk at index %d is in the wrong mode: requested=%s found=%s"
                        % (i, disk_modes[i], attached_disk['mode'])))
                else:
                    continue
            gce.attach_volume(inst, lc_disk, ex_mode=disk_modes[i])
            # Work around libcloud bug: attached volumes don't get added
            # to the instance metadata. get_instance_info() only cares about
            # source and index.
            if len(inst.extra['disks']) != i + 1:
                inst.extra['disks'].append({
                    'source': lc_disk.extra['selfLink'],
                    'index': i
                })

    instance_names = []
    instance_json_data = []
    for inst in new_instances:
        d = get_instance_info(inst)
        instance_names.append(d['name'])
        instance_json_data.append(d)

    return (changed, instance_json_data, instance_names)
Exemplo n.º 51
0
    def run(self):
        """
            Start our packet capture logging all dropped packets.
            
            In this context we consider a packet to be dropped if we there is 
        """
     
        # Initialize our capture
        pc = pcap.pcap(self.interface)
        pc.setfilter('udp')
        
        # initialize our variables used for comparison
        last_id = None
        sensor_ip_int = socket.inet_aton(self.sensor_ip)
        total_packets = dropped_packets = 0
        # Initialize our dict
        self.return_values['total'] = 0
        self.return_values['dropped'] = 0
        self.return_values['data_received'] = 0
        
        logger.debug("Starting packet capture")
        for ts, pkt in pc:
                
            # Start analyzing our packet
            eth_packet = dpkt.ethernet.Ethernet(pkt)

            

            # We only care about ethernet frames        
            if eth_packet.type != dpkt.ethernet.ETH_TYPE_IP:
                continue
                
            ip_packet = eth_packet.data

            # UDP packet from the IP we are listening too?
            if ip_packet.src == sensor_ip_int and ip_packet.p == dpkt.ip.IP_PROTO_UDP:
                
                    self.return_values['data_received'] += len(eth_packet)
                    
                    total_packets += 1
                    self.return_values['total'] = total_packets
                    
                    # Update the last packet id
                    if last_id is None:
                        last_id = ip_packet.id
                        
                    # packet id be incremental, if it's not, we lost packets
                    elif ip_packet.id > last_id+1:
                        
                        dropped = ip_packet.id - last_id - 1
                        dropped_packets += dropped
                        total_packets += dropped
                        
                        self.return_values['dropped'] = dropped_packets
                        
                        logger.debug("[%f] Dropped packet(s). (%d/%d) (c: %d, p:%d)"%(
                                                                float(dropped_packets)/float(total_packets),
                                                                dropped_packets,
                                                                total_packets,
                                                                ip_packet.id,
                                                                last_id))
                    elif ip_packet.id < last_id and ip_packet.id > 0:
                        dropped = ip_packet.id - 1 + (0xffff - last_id)
                        dropped_packets += dropped
                        total_packets += dropped
                        
                        self.return_values['dropped'] = dropped_packets
                        
                        logger.debug("[%f] Dropped packet(s). (%d/%d) (c: %d, p:%d)"%(
                                                                float(dropped_packets)/float(total_packets),
                                                                dropped_packets,
                                                                total_packets,
                                                                ip_packet.id,
                                                                last_id))
                        
                    # Update our total states
                    last_id = ip_packet.id
                    
            if dropped_packets > total_packets:
                logger.error("DROPPED MORE THAN WE SAW!")
                break
Exemplo n.º 52
0
def ipToLong(ip):  #ip地址到整形
    IP = socket.inet_aton(ip)
    return struct.unpack("!L", IP)[0]
Exemplo n.º 53
0
 def src_ip(self, src_ip):
     self.__src_ip = socket.inet_aton(src_ip)
Exemplo n.º 54
0
def invalid_ip(addr):
    try:
        socket.inet_aton(addr)
    except:
        return True
    return False
Exemplo n.º 55
0
 def is_valid_ip(self, ip_str):
     try:
         socket.inet_aton(ip_str)
         return True
     except socket.error:
         return False
Exemplo n.º 56
0
 def dest_ip(self, dest_ip):
     self.__dest_ip = socket.inet_aton(dest_ip)
Exemplo n.º 57
0
from config import AudioConf as ac
from config import NetConf as nc

pa = pyaudio.PyAudio()
stream = pa.open(format=pa.get_format_from_width(ac.WIDTH),
                 channels=ac.CHANNELS,
                 rate=ac.RATE,
                 output=True,
                 start=False,
                 frames_per_buffer=ac.CHUNK)

multicast_addr = nc.ADDR
port = nc.PORT
bind_addr = '0.0.0.0'

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
membership = socket.inet_aton(multicast_addr) + socket.inet_aton(bind_addr)

sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, membership)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

sock.bind((bind_addr, port))

stream.start_stream()
while True:
    data, address = sock.recvfrom(ac.CHUNK)
    stream.write(data)
    print(data, address)
stream.stop_stream()
Exemplo n.º 58
0
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)5s: %(message)s')

# Color the errors and warnings in red
logging.addLevelName(logging.ERROR, "\033[91m  %s\033[0m" % logging.getLevelName(logging.ERROR))
logging.addLevelName(logging.WARNING, "\033[91m%s\033[0m" % logging.getLevelName(logging.WARNING))
log = logging.getLogger(__name__)

parser = argparse.ArgumentParser(description='Multicast RX utility',
                                 version='1.0.0')
parser.add_argument('group', help='Multicast IP')
parser.add_argument('ifname', help='Interface name')
parser.add_argument('--port', help='UDP port', default=1000)
parser.add_argument('--sleep', help='Time to sleep before we stop waiting',
                    default = 5)
args = parser.parse_args()

# Create the datagram socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((args.group, args.port))

newpid = os.fork()

if newpid == 0:
    ifindex = ifname_to_ifindex(args.ifname)
    mreq = struct.pack("=4sLL", socket.inet_aton(args.group), socket.INADDR_ANY, ifindex)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    time.sleep(float(args.sleep))
    sock.close()
Exemplo n.º 59
0
def ipv4int(valu):
    try:
        byts = socket.inet_aton(valu)
        return struct.unpack('>I', byts)[0]
    except socket.error as e:
        raise BadTypeValu(valu=valu, type='inet:ipv4', mesg=str(e))
Exemplo n.º 60
0
def to_match(dp, attrs):
    ofp = dp.ofproto

    wildcards = ofp.OFPFW_ALL
    LOG.debug('VLOG In to_match OFPFW_ALL %d', ofp.OFPFW_ALL)  #CEP
    LOG.debug('VLOG In to_match OFPFW_TP_DST %d', ofp.OFPFW_TP_DST)  #CEP
    LOG.debug('VLOG In to_match OFPFW_EVNT_ATTR1 %d',
              ofp.OFPFW_EVNT_ATTR1)  #CEP
    LOG.debug('VLOG In to_match OFPFW_EVNT_ATTR2 %d',
              ofp.OFPFW_EVNT_ATTR2)  #CEP
    in_port = 0
    dl_src = 0
    dl_dst = 0
    dl_vlan = 0
    dl_vlan_pcp = 0
    dl_type = 0
    nw_tos = 0
    nw_proto = 0
    nw_src = 0
    nw_dst = 0
    tp_src = 0
    tp_dst = 0
    e_attr1 = 0
    e_attr2 = 0
    e_type = 0
    e_val1 = 0

    for key, value in attrs.items():
        if key == 'in_port':
            in_port = UTIL.ofp_port_from_user(value)
            wildcards &= ~ofp.OFPFW_IN_PORT
            LOG.debug(
                'VLOG In to_match point -1  OFPFW_IN_PORT - %d wildcards - %d',
                ofp.OFPFW_IN_PORT, wildcards)  #CEP
        elif key == 'dl_src':
            dl_src = haddr_to_bin(value)
            wildcards &= ~ofp.OFPFW_DL_SRC
            LOG.debug(
                'VLOG In to_match point -2  OFPFW_DL_SRC - %d wildcards - %d',
                ofp.OFPFW_DL_SRC, wildcards)  #CEP
        elif key == 'dl_dst':
            dl_dst = haddr_to_bin(value)
            wildcards &= ~ofp.OFPFW_DL_DST
            LOG.debug(
                'VLOG In to_match point -3  OFPFW_DL_DST - %d wildcards - %d',
                ofp.OFPFW_DL_DST, wildcards)  #CEP
        elif key == 'dl_vlan':
            dl_vlan = int(value)
            wildcards &= ~ofp.OFPFW_DL_VLAN
            LOG.debug(
                'VLOG In to_match point -4  OFPFW_DL_VLAN - %d wildcards - %d',
                ofp.OFPFW_DL_VLAN, wildcards)  #CEP
        elif key == 'dl_vlan_pcp':
            dl_vlan_pcp = int(value)
            wildcards &= ~ofp.OFPFW_DL_VLAN_PCP
            LOG.debug(
                'VLOG In to_match point -5  OFPFW_DL_VLAN_PCP - %d wildcards - %d',
                ofp.OFPFW_DL_VLAN_PCP, wildcards)  #CEP
        elif key == 'dl_type':
            dl_type = int(value)
            wildcards &= ~ofp.OFPFW_DL_TYPE
            LOG.debug(
                'VLOG In to_match point -6  OFPFW_DL_TYPE - %d wildcards - %d',
                ofp.OFPFW_DL_TYPE, wildcards)  #CEP
        elif key == 'nw_tos':
            nw_tos = int(value)
            wildcards &= ~ofp.OFPFW_NW_TOS
            LOG.debug(
                'VLOG In to_match point -7  OFPFW_NW_TOS - %d wildcards - %d',
                ofp.OFPFW_NW_TOS, wildcards)  #CEP
        elif key == 'nw_proto':
            nw_proto = int(value)
            wildcards &= ~ofp.OFPFW_NW_PROTO
            LOG.debug(
                'VLOG In to_match point -8  OFPFW_NW_PROTO - %d wildcards - %d',
                ofp.OFPFW_NW_PROTO, wildcards)  #CEP
        elif key == 'nw_src':
            ip = value.split('/')
            nw_src = struct.unpack('!I', socket.inet_aton(ip[0]))[0]
            mask = 32
            if len(ip) == 2:
                mask = int(ip[1])
                assert 0 < mask <= 32
            v = (32 - mask) << ofp.OFPFW_NW_SRC_SHIFT | \
                ~ofp.OFPFW_NW_SRC_MASK
            wildcards &= v
            LOG.debug(
                'VLOG In to_match point -9  OFPFW_NW_SRC_SHIFT - %d, OFPFW_NW_SRC_MASK - %d, v - %d,  wildcards - %d',
                ofp.OFPFW_NW_SRC_SHIFT, ofp.OFPFW_NW_SRC_MASK, v,
                wildcards)  #CEP
        elif key == 'nw_dst':
            ip = value.split('/')
            nw_dst = struct.unpack('!I', socket.inet_aton(ip[0]))[0]
            mask = 32
            if len(ip) == 2:
                mask = int(ip[1])
                assert 0 < mask <= 32
            v = (32 - mask) << ofp.OFPFW_NW_DST_SHIFT | \
                ~ofp.OFPFW_NW_DST_MASK
            wildcards &= v
            LOG.debug(
                'VLOG In to_match point -10  OFPFW_NW_DST_SHIFT - %d, OFPFW_NW_SRC_MASK - %d, v - %d,  wildcards - %d',
                ofp.OFPFW_NW_DST_SHIFT, ofp.OFPFW_NW_DST_MASK, v,
                wildcards)  #CEP
        elif key == 'tp_src':
            tp_src = int(value)
            wildcards &= ~ofp.OFPFW_TP_SRC
            LOG.debug(
                'VLOG In to_match point -11  OFPFW_TP_SRC - %d wildcards - %d',
                ofp.OFPFW_TP_SRC, wildcards)  #CEP
        elif key == 'tp_dst':
            tp_dst = int(value)
            wildcards &= ~ofp.OFPFW_TP_DST
            LOG.debug(
                'VLOG In to_match point -12  OFPFW_TP_DST - %d wildcards - %d',
                ofp.OFPFW_TP_DST, wildcards)  #CEP
        elif key == 'e_attr1':
            e_attr1 = int(value)
            wildcards &= ~ofp.OFPFW_EVNT_ATTR1
            LOG.debug(
                'VLOG In to_match point -13  OFPFW_EVNT_ATTR1 - %d wildcards - %d',
                ofp.OFPFW_EVNT_ATTR1, wildcards)  #CEP
        elif key == 'e_attr2':
            e_attr2 = int(value)
            wildcards &= ~ofp.OFPFW_EVNT_ATTR2
            LOG.debug(
                'VLOG In to_match point -14  OFPFW_EVNT_ATTR2 - %d wildcards - %d',
                ofp.OFPFW_EVNT_ATTR2, wildcards)  #CEP
        elif key == 'e_type':
            strval = ""
            for k in value:
                strval += format(ord(k), "d")
            e_type = int(strval)
            wildcards &= ~ofp.OFPFW_EVNT_TYP
            LOG.debug(
                'VLOG In to_match point -14  OFPFW_EVNT_TYP - %d wildcards - %d',
                ofp.OFPFW_EVNT_TYP, wildcards)  #CEP
        elif key == 'e_val1':
            e_val1 = int(value)
            wildcards &= ~ofp.OFPFW_EVNT_VAL1
            LOG.debug(
                'VLOG In to_match point -14  OFPFW_EVNT_VAL1 - %d wildcards - %d',
                ofp.OFPFW_EVNT_VAL1, wildcards)  #CEP

        else:
            LOG.error("unknown match name %s, %s, %d", key, value, len(key))

    LOG.debug(
        'VLOG In ofctl_v1_0 to_match point -15  e_attr1 - %d e_attr2 - %d e_type - %d',
        e_attr1, e_attr2, e_type)  #CEP
    match = dp.ofproto_parser.OFPMatch(wildcards, in_port, dl_src, dl_dst,
                                       dl_vlan, dl_vlan_pcp, dl_type, nw_tos,
                                       nw_proto, nw_src, nw_dst, tp_src,
                                       tp_dst, e_attr1, e_attr2, e_type,
                                       e_val1)

    return match