Python socket.inet_aton() Examples

The following are code examples for showing how to use socket.inet_aton(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: aridi   Author: dpgon   File: scan.py    GNU General Public License v3.0 8 votes vote down vote up
def _arppacket(destip, sourceip, sourcemac, iface):
    sourcemac = unhexlify(sourcemac.replace(':', ''))
    broadmac = b'\xFF\xFF\xFF\xFF\xFF\xFF'

    s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(3))
    s.bind((iface, socket.htons(3)))

    # Ethernet Header
    protocol = 0x0806   # 0x0806 for ARP
    eth_hdr = pack("!6s6sH", broadmac, sourcemac, protocol)

    # ARP header
    htype = 0x0001      # Hardware type ethernet
    ptype = 0x0800      # Protocol type TCP
    hlen = 0x06         # Hardware address Len
    plen = 0x04         # Protocol addr. len
    operation = 0x0001  # 1=request/2=reply
    src_ip = socket.inet_aton(sourceip)
    dst_ip = socket.inet_aton(destip)
    arp_hdr = pack("!HHBBH6s4s6s4s", htype, ptype, hlen, plen,
                   operation, sourcemac, src_ip, broadmac, dst_ip)

    packet = eth_hdr + arp_hdr

    s.send(packet) 
Example 2
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 3
Project: flasky   Author: RoseOu   File: utils.py    MIT License 6 votes vote down vote up
def is_valid_cidr(string_network):
    """Very simple check of the cidr format in no_proxy variable"""
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 4
Project: sic   Author: Yanixos   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 5
Project: bigquerylayers   Author: smandaric   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 6
Project: AshsSDK   Author: thehappydinoa   File: utils.py    MIT License 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 7
Project: yz   Author: 6r6   File: utils.py    MIT License 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 8
Project: Paradrop   Author: ParadropLabs   File: addresses.py    Apache License 2.0 6 votes vote down vote up
def maxIpaddr(ipaddr, netmask):
    """
        Takes a quad dot format IP address string and makes it the largest valid value still in the same subnet.

        Returns:
            Max quad dot IP string or None if error
    """
    try:
        val = struct.unpack("!I", socket.inet_aton(ipaddr))[0]
        nm = struct.unpack("!I", socket.inet_aton(netmask))[0]
        inc = struct.unpack("!I", socket.inet_aton("0.0.0.254"))[0]
        val &= nm
        val |= inc
        return socket.inet_ntoa(struct.pack('!I', val))
    except Exception:
        return None 
Example 9
Project: Kitsu.Bundle   Author: AeonLucid   File: utils.py    MIT License 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 10
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 6 votes vote down vote up
def inet_pton(address_family, ip_string):
        if address_family == socket.AF_INET:
            return socket.inet_aton(ip_string)

        addr = sockaddr()
        addr.sa_family = address_family
        addr_size = ctypes.c_int(ctypes.sizeof(addr))

        if WSAStringToAddressA(
                ip_string,
                address_family,
                None,
                ctypes.byref(addr),
                ctypes.byref(addr_size)
        ) != 0:
            raise socket.error(ctypes.FormatError())

        if address_family == socket.AF_INET6:
            return ctypes.string_at(addr.ipv6_addr, 16)

        raise socket.error('unknown address family') 
Example 11
Project: jawfish   Author: war-and-code   File: utils.py    MIT License 6 votes vote down vote up
def is_valid_cidr(string_network):
    """Very simple check of the cidr format in no_proxy variable"""
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 12
Project: Repobot   Author: Desgard   File: utils.py    MIT License 6 votes vote down vote up
def is_valid_cidr(string_network):
    """
    Very simple check of the cidr format in no_proxy variable.

    :rtype: bool
    """
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 13
Project: lena   Author: coingraham   File: utils.py    MIT License 6 votes vote down vote up
def is_valid_cidr(string_network):
    """Very simple check of the cidr format in no_proxy variable"""
    if string_network.count('/') == 1:
        try:
            mask = int(string_network.split('/')[1])
        except ValueError:
            return False

        if mask < 1 or mask > 32:
            return False

        try:
            socket.inet_aton(string_network.split('/')[0])
        except socket.error:
            return False
    else:
        return False
    return True 
Example 14
Project: gist-alfred   Author: danielecook   File: ssl_.py    MIT License 6 votes vote down vote up
def inet_pton(_, host):
            return socket.inet_aton(host)


# A secure default.
# Sources for more information on TLS ciphers:
#
# - https://wiki.mozilla.org/Security/Server_Side_TLS
# - https://www.ssllabs.com/projects/best-practices/index.html
# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
#
# The general intent is:
# - Prefer TLS 1.3 cipher suites
# - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
# - prefer ECDHE over DHE for better performance,
# - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and
#   security,
# - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,
# - disable NULL authentication, MD5 MACs and DSS for security reasons. 
Example 15
Project: incubator-spot   Author: apache   File: common.py    Apache License 2.0 5 votes vote down vote up
def parse_ip_literal(ast):
    socket.inet_aton(ast.value)

    return ast.value 
Example 16
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testIPv4_inet_aton_fourbytes(self):
        # Test that issue1008086 and issue767150 are fixed.
        # It must return 4 bytes.
        self.assertEqual('\x00'*4, socket.inet_aton('0.0.0.0'))
        self.assertEqual('\xff'*4, socket.inet_aton('255.255.255.255')) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testIPv4toString(self):
        from socket import inet_aton as f, inet_pton, AF_INET
        g = lambda a: inet_pton(AF_INET, a)

        self.assertEqual('\x00\x00\x00\x00', f('0.0.0.0'))
        self.assertEqual('\xff\x00\xff\x00', f('255.0.255.0'))
        self.assertEqual('\xaa\xaa\xaa\xaa', f('170.170.170.170'))
        self.assertEqual('\x01\x02\x03\x04', f('1.2.3.4'))
        self.assertEqual('\xff\xff\xff\xff', f('255.255.255.255'))

        self.assertEqual('\x00\x00\x00\x00', g('0.0.0.0'))
        self.assertEqual('\xff\x00\xff\x00', g('255.0.255.0'))
        self.assertEqual('\xaa\xaa\xaa\xaa', g('170.170.170.170'))
        self.assertEqual('\xff\xff\xff\xff', g('255.255.255.255')) 
Example 18
Project: iSDX   Author: sdn-ixp   File: utils.py    Apache License 2.0 5 votes vote down vote up
def craft_arp_packet(packet, dst_mac):
    arp_packet = [
        packet["htype"],
        packet["ptype"],
        packet["hlen"],
        packet["plen"],
        struct.pack("!h", 2),
        binascii.unhexlify(dst_mac.replace(':', '')),
        socket.inet_aton(packet["dst_ip"]),
        binascii.unhexlify(packet["src_mac"].replace(':', '')),
        socket.inet_aton(packet["src_ip"])]

    return arp_packet 
Example 19
Project: iSDX   Author: sdn-ixp   File: utils.py    Apache License 2.0 5 votes vote down vote up
def craft_garp_response(SPA, TPA, SHA, THA, eth_src, eth_dst):
    "Craft Gratuitous ARP Response Message"
    """
    Format ARP reply:
    eth_src = VMAC, eth_dst = requester_mac, SHA = VMAC, SPA = vnhip, THA = requester_mac, TPA = requester_ip

    Format gratuitous ARP:
    eth_src = VMAC, eth_dst = 00..00<part_id>, SHA = VMAC, SPA = vnhip, THA = VMAC, TPA = vnhip
    """
    arp_packet = [
        # HTYPE
        struct.pack("!h", 1),
        # PTYPE (IPv4)
        struct.pack("!h", 0x0800),
        # HLEN
        struct.pack("!B", 6),
        # PLEN
        struct.pack("!B", 4),
        # OPER (reply)
        struct.pack("!h", 2),
        # SHA
        binascii.unhexlify(SHA.replace(':', '')),
        # SPA
        socket.inet_aton(str(SPA)),
        # THA
        binascii.unhexlify(THA.replace(':', '')),
        # TPA
        socket.inet_aton(str(TPA))
    ]
    eth_frame = [
        # Destination address:
        binascii.unhexlify(eth_dst.replace(':', '')),
        # Source address:
        binascii.unhexlify(eth_src.replace(':', '')),
        # Protocol
        struct.pack("!h", ETH_TYPE_ARP),
        # Data
        ''.join(arp_packet)
    ]
    return ''.join(eth_frame) 
Example 20
Project: iSDX   Author: sdn-ixp   File: decision_process.py    Apache License 2.0 5 votes vote down vote up
def ip_to_long(ip):
    return struct.unpack('!L', socket.inet_aton(ip))[0] 
Example 21
Project: GAZE   Author: monokal   File: helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def is_ipv4_address(self, string):
        """
        Check if a string is a valid IPv4 address or not.
        :param string: (str) The string to check IPv4 address validity against.
        :return: (bool) Whether string is a valid IPv4 address or not.
        """

        try:
            socket.inet_aton(string)

        except:
            return False

        return True 
Example 22
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 5 votes vote down vote up
def address_in_network(ip, net):
    """This function allows you to check if an IP belongs to a network subnet

    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24

    :rtype: bool
    """
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask) 
Example 23
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 5 votes vote down vote up
def is_ipv4_address(string_ip):
    """
    :rtype: bool
    """
    try:
        socket.inet_aton(string_ip)
    except socket.error:
        return False
    return True 
Example 24
Project: flasky   Author: RoseOu   File: utils.py    MIT License 5 votes vote down vote up
def address_in_network(ip, net):
    """
    This function allows you to check if on IP belongs to a network subnet
    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
    """
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask) 
Example 25
Project: flasky   Author: RoseOu   File: utils.py    MIT License 5 votes vote down vote up
def is_ipv4_address(string_ip):
    try:
        socket.inet_aton(string_ip)
    except socket.error:
        return False
    return True 
Example 26
Project: flasky   Author: RoseOu   File: utils.py    MIT License 5 votes vote down vote up
def address_in_network(ip, net):
    """
    This function allows you to check if on IP belongs to a network subnet
    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
    """
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask) 
Example 27
Project: flasky   Author: RoseOu   File: utils.py    MIT License 5 votes vote down vote up
def is_ipv4_address(string_ip):
    try:
        socket.inet_aton(string_ip)
    except socket.error:
        return False
    return True 
Example 28
Project: isolate   Author: itsumma   File: IsolateCore.py    MIT License 5 votes vote down vote up
def is_valid_ipv4_address(address):
    try:
        socket.inet_pton(socket.AF_INET, address)
    except AttributeError:
        try:
            socket.inet_aton(address)
        except socket.error:
            return False
        return True
    except socket.error:
        return False

    return True 
Example 29
Project: isolate   Author: itsumma   File: helper.py    MIT License 5 votes vote down vote up
def is_valid_ipv4(address):
        try:
            socket.inet_pton(socket.AF_INET, address)
        except AttributeError:  # no inet_pton here, sorry
            try:
                socket.inet_aton(address)
            except socket.error:
                return False
            return True
        except socket.error:  # not a valid address
            return False

        return True 
Example 30
Project: isolate   Author: itsumma   File: ssh.py    MIT License 5 votes vote down vote up
def is_valid_ipv4_address(address):
    try:
        socket.inet_pton(socket.AF_INET, address)
    except AttributeError:
        try:
            socket.inet_aton(address)
        except socket.error:
            return False
        return True
    except socket.error:
        return False

    return True 
Example 31
Project: XFLTReaT   Author: earthquake   File: DNS.py    MIT License 5 votes vote down vote up
def do_hello(self):
		# TODO: maybe change this later to push some more info, not only the 
		# private IP
		message = socket.inet_aton(self.config.get("Global", "clientip"))
		self.send(common.CONTROL_CHANNEL_BYTE, common.CONTROL_INIT+message, 
			 (self.server_tuple, 0, None))

	# Polite signal towards the server to tell that the client is leaving
	# Can be spoofed? if there is no encryption. Who cares? 
Example 32
Project: XFLTReaT   Author: earthquake   File: ICMP.py    MIT License 5 votes vote down vote up
def lookup_client_pub(self, additional_data):
		addr = additional_data[0]
		identifier = additional_data[1]
		client_public_ip = socket.inet_aton(addr[0])

		for c in self.clients:
			if (c.get_public_ip_addr() == client_public_ip) and (c.get_ICMP_received_identifier() == identifier):
				return c

		return None 
Example 33
Project: XFLTReaT   Author: earthquake   File: ICMP.py    MIT License 5 votes vote down vote up
def do_hello(self):
		# TODO: maybe change this later to push some more info, not just the 
		# private IP
		message = socket.inet_aton(self.config.get("Global", "clientip"))
		self.send(common.CONTROL_CHANNEL_BYTE, common.CONTROL_INIT+message, 
			(self.server_tuple, self.ICMP_identifier, self.ICMP_sequence, 0))

	# Polite signal towards the server to tell that the client is leaving
	# Can be spoofed? if there is no encryption. Who cares? 
Example 34
Project: XFLTReaT   Author: earthquake   File: UDP_generic.py    MIT License 5 votes vote down vote up
def do_hello(self):
		# TODO: maybe change this later to push some more info, not just the 
		# private IP
		message = socket.inet_aton(self.config.get("Global", "clientip"))
		self.send(common.CONTROL_CHANNEL_BYTE, common.CONTROL_INIT+message, (self.server_tuple, None))

	# Polite signal towards the server to tell that the client is leaving
	# Can be spoofed? if there is no encryption. Who cares? 
Example 35
Project: XFLTReaT   Author: earthquake   File: Stateless_module.py    MIT License 5 votes vote down vote up
def lookup_client_pub(self, additional_data):
		addr = additional_data[0]
		client_public_ip = socket.inet_aton(addr[0])

		for c in self.clients:
			if (c.get_public_ip_addr() == client_public_ip) and (c.get_public_src_port() == addr[1]):
				return c

		return None

	# find the encryption details of the client 
Example 36
Project: XFLTReaT   Author: earthquake   File: dns_proto.py    MIT License 5 votes vote down vote up
def build_record_A(self, record):
		additional_record_num = 0
		additional_records = ""
		answer_num = 1
		answers = struct.pack(">HHHIH", 0xc00c, 1, 1, 5, 4) + socket.inet_aton(record[2]) 

		return (answer_num, answers, additional_record_num, additional_records) 
Example 37
Project: XFLTReaT   Author: earthquake   File: dns_proto.py    MIT License 5 votes vote down vote up
def build_record_NS(self, record):
		additional_record_num = 0
		additional_records = ""
		compress_hostname = self.hostname_to_hostnamebin(record[2])

		answer_num = 1
		answers = struct.pack(">HHHIH", 0xc00c, 2, 1, 3600, len(compress_hostname)) + compress_hostname
		
		#additional_record_num = 1
		#additional_records = compress_hostname + struct.pack(">HHIH", 1, 1, 5, 4) + socket.inet_aton("1.1.1.1")

		return (answer_num, answers, additional_record_num, additional_records) 
Example 38
Project: XFLTReaT   Author: earthquake   File: dns_proto.py    MIT License 5 votes vote down vote up
def build_record_ANY(self, record):
		compress_hostname = self.hostname_to_hostnamebin(record[2])
		additional_record_num = 0
		additional_records = ""

		answer_num = 2
		answers =  struct.pack(">HHHIH", 0xc00c, 5, 1, 5, len(compress_hostname)) + compress_hostname
		answers += struct.pack(">HHHIH", 0xc00c, 1, 1, 5, 4) + socket.inet_aton(record[3])
		
		return (answer_num, answers, additional_record_num, additional_records) 
Example 39
Project: XFLTReaT   Author: earthquake   File: interface.py    MIT License 5 votes vote down vote up
def lin_set_ip_address(self, dev, ip, serverip, netmask):
		sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			# set IP
			ifr  = struct.pack('<16sH2s4s8s', dev, socket.AF_INET, "\x00"*2, socket.inet_aton(ip), "\x00"*8)
			fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFADDR, ifr)

			# get flags
			ifr = struct.pack('<16sh', dev, 0)
			flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr))[1]

			# set new flags
			flags = flags | self.IOCTL_LINUX_IFF_UP
			ifr = struct.pack('<16sh', dev, flags)

			# iface up
			fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))

		integer_netmask = struct.pack(">I", ((2**int(netmask))-1)<<32-int(netmask))
		netmask = socket.inet_ntoa(integer_netmask)

		ps = subprocess.Popen(["route", "add", "-net", rangeip, "netmask", netmask, "dev", dev], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example 40
Project: XFLTReaT   Author: earthquake   File: interface.py    MIT License 5 votes vote down vote up
def freebsd_set_ip_address(self, dev, ip, serverip, netmask):
		sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			#set ip, serverip and netmask
			ifaliasreq = struct.pack('<16sBBHI8sBBHI8sBBHI8sI', self.iface_name,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(ip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(serverip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton('255.255.255.255'))[0],
				'\x00'*8,
				0)
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCAIFADDR, ifaliasreq)

			# get flags
			ifr = struct.pack('<16sh', self.iface_name, 0)
			flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCGIFFLAGS, ifr))[1]

			# set new flags
			flags = flags | self.IOCTL_FREEBSD_IFF_UP
			ifr = struct.pack('<16sh', self.iface_name, flags)

			# iface up
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFFLAGS, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))

		ps = subprocess.Popen(["route", "add", "-net", rangeip+"/"+netmask, serverip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example 41
Project: sic   Author: Yanixos   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def address_in_network(ip, net):
    """This function allows you to check if on IP belongs to a network subnet

    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24

    :rtype: bool
    """
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask) 
Example 42
Project: sic   Author: Yanixos   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def is_ipv4_address(string_ip):
    """
    :rtype: bool
    """
    try:
        socket.inet_aton(string_ip)
    except socket.error:
        return False
    return True 
Example 43
Project: bigquerylayers   Author: smandaric   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def address_in_network(ip, net):
    """This function allows you to check if an IP belongs to a network subnet

    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24

    :rtype: bool
    """
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask) 
Example 44
Project: bigquerylayers   Author: smandaric   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def is_ipv4_address(string_ip):
    """
    :rtype: bool
    """
    try:
        socket.inet_aton(string_ip)
    except socket.error:
        return False
    return True 
Example 45
Project: smbprotocol   Author: jborean93   File: exceptions.py    MIT License 5 votes vote down vote up
def set_ipaddress(self, address):
        # set's the IP address from a human readable format, for IPv6, this
        # needs to be the full IPv6 address
        if self['type'].get_value() == IpAddrType.MOVE_DST_IPADDR_V4:
            self['ip_address'].set_value(socket.inet_aton(address))
        else:
            addr = address.replace(":", "")
            if len(addr) != 32:
                raise ValueError("When setting an IPv6 address, it must be in "
                                 "the full form without concatenation")
            self['ip_address'].set_value(binascii.unhexlify(addr)) 
Example 46
Project: smbprotocol   Author: jborean93   File: ioctl.py    MIT License 5 votes vote down vote up
def set_ipaddress(self, address):
        # set's the ipv4 address field from the address string passed in, this
        # needs to be the full ipv4 address including periods, e.g.
        # 192.168.1.1
        addr_bytes = socket.inet_aton(address)
        self['ipv4_address'].set_value(addr_bytes) 
Example 47
Project: AshsSDK   Author: thehappydinoa   File: utils.py    MIT License 5 votes vote down vote up
def address_in_network(ip, net):
    """This function allows you to check if on IP belongs to a network subnet

    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24

    :rtype: bool
    """
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask) 
Example 48
Project: AshsSDK   Author: thehappydinoa   File: utils.py    MIT License 5 votes vote down vote up
def is_ipv4_address(string_ip):
    """
    :rtype: bool
    """
    try:
        socket.inet_aton(string_ip)
    except socket.error:
        return False
    return True 
Example 49
Project: AshsSDK   Author: thehappydinoa   File: utils.py    MIT License 5 votes vote down vote up
def address_in_network(ip, net):
    """
    This function allows you to check if on IP belongs to a network subnet
    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
    """
    ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
    netaddr, bits = net.split('/')
    netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
    network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
    return (ipaddr & netmask) == (network & netmask) 
Example 50
Project: AshsSDK   Author: thehappydinoa   File: utils.py    MIT License 5 votes vote down vote up
def is_ipv4_address(string_ip):
    try:
        socket.inet_aton(string_ip)
    except socket.error:
        return False
    return True