Python struct.pack() Examples

The following are 30 code examples of struct.pack(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module struct , or try the search function .
Example #1
Source File: DNS.py    From XFLTReaT with MIT License 8 votes vote down vote up
def cmh_autotune(self, module, message, additional_data, cm):
		message = message[len(self.CONTROL_AUTOTUNE)+2:]
		# get tune type, requested record type, length and encoding for crafting the answer
		(query_type, RRtype, length, encode_class) = struct.unpack("<BHHH", message[0:7])
		if self.DNS_proto.get_RR_type(RRtype)[0] == None:
			return True
		
		# extra parameters added to be able to response in the proper way
		additional_data = additional_data + (True, self.download_encoding_list[encode_class], self.DNS_proto.get_RR_type(RRtype)[0])		
		if (query_type == 0) or (query_type == 3):
			# record && downstream length discovery
			message = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))
		if query_type == 1:
			# A record name length discovery
			message = struct.pack("<i", binascii.crc32(message[7:]))
		if query_type == 2:
			# checking download encoding, echoing back request payload
			message = message[7:]

		module.send(common.CONTROL_CHANNEL_BYTE, self.CONTROL_AUTOTUNE_CLIENT+message, additional_data)
		return True

	# tune control message handler
	# client sets the record type and encodings by calling this
	# server side 
Example #2
Source File: dns_proto.py    From XFLTReaT with MIT License 6 votes vote down vote up
def build_answer(self, transaction_id, record, orig_question):
		if record == None:
			flag = 0x8503 # 1000 0100 0000 0011
			answer_num = 0
			answers = ""
			additional_record_num = 0
			additional_records = ""
		else:
			flag = 0x8500 #	1000 0100 0000 0000
			RRtype = self.reverse_RR_type(record[0])
			if RRtype[1] == None:
				answer_num = 0
				answers = ""
				additional_record_num = 0
				additional_records = ""
			else:
				answer_num = 1
				(answer_num, answers, additional_record_num, additional_records) = RRtype[1](record)

		dns_header = struct.pack(">HHHHHH", transaction_id, flag, 1, answer_num, 0, additional_record_num)

		return dns_header + orig_question + answers + additional_records 
Example #3
Source File: cache.py    From vergeml with MIT License 6 votes vote down vote up
def __init__(self, path, mode):
        assert mode in ("r", "w")

        self.path = path
        self.file = open(self.path, mode + "b")
        self.mmfile = None
        self.mode = mode
        self.cnt = _CacheFileContent()

        if mode == "r":
            # Read the last part of the file which contains the contents of the
            # cache.
            self.cnt.read(self.file, self.path)
            self.mmfile = mmap.mmap(self.file.fileno(), 0, access=mmap.ACCESS_READ)
        else:
            # The 8 bytes header contain the position of the content index.
            # We fill this header with zeroes and write the actual position
            # once all samples have been written to the cache
            self.file.write(struct.pack('<Q', 0)) 
Example #4
Source File: addresses.py    From Paradrop with 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 #5
Source File: ogg.py    From ALF with Apache License 2.0 6 votes vote down vote up
def fuzz(self, fuzzer):
        """Return a fuzzed version of this page."""
        # TODO, for these vorbis header pages, should fuzz the parameters within structures
        # https://www.xiph.org/vorbis/doc/Vorbis_I_spec.html#x1-600004.2
        #print "fuzz",
        if self.special == b"\x01vorbis":
            #print "spc1",
            hdr = self.fuzz_header(fuzzer)
            vorbhdr = bytes(fuzzer(self.data[0][7:])[:22])
            data = [b"".join([b"\x01vorbis", vorbhdr, b"\x01" * (23 - len(vorbhdr))])]
        elif self.special: # unknown "special" page
            #print "spcx (k)"
            return b"".join([self.header] + self.data)
        else:
            #print "nspc",
            hdr = self.fuzz_header(fuzzer)
            data = [bytes(fuzzer(i)[:255]) for i in self.data[:255]]
        out = b"".join([hdr, bytes([len(data)])] + [bytes([len(i)]) for i in data] + data)
        pagecrc = ogg_crc32(out)
        out = b"".join([out[:22], struct.pack("<I", pagecrc), out[26:]])
        #print "ok"
        return out 
Example #6
Source File: usbmux.py    From facebook-wda with MIT License 6 votes vote down vote up
def send_packet(self, payload: dict, reqtype: int = 8):
        """
        Args:
            payload: required

            # The following args only used in the first request
            reqtype: request type, always 8 
            tag: int
        """
        body_data = plistlib.dumps(payload)
        if self._first:  # first package
            length = 16 + len(body_data)
            header = struct.pack(
                "IIII", length, 1, reqtype,
                self._tag)  # version: 1, request: 8(?), tag: 1(?)
        else:
            header = struct.pack(">I", len(body_data))
        self.sendall(header + body_data) 
Example #7
Source File: ipmisim.py    From ipmisim with Apache License 2.0 6 votes vote down vote up
def __new__(cls, *args, **kwargs):
        if cls.__instance == None or (len(args) > 0 and args[0] == 'reset'):
            cls.__instance = object.__new__(cls)
            cls.__instance.name = "IpmiServer Context"

            # Initialize ctx state
            self = cls.__instance
            self.device_name = "CloudStack IPMI Sim"
            self.sessions = dict()
            self.uuid = uuid.uuid4()
            self.kg = None
            self.authdata = collections.OrderedDict()

            lanchannel = 1
            authtype = 0b10000000
            authstatus = 0b00000100
            chancap = 0b00000010
            oemdata = (0, 0, 0, 0)
            self.authcap = struct.pack('BBBBBBBBB', 0, lanchannel, authtype, authstatus, chancap, *oemdata)
            self.bmc = self._configure_users()
            logger.info('CloudStack IPMI Sim BMC initialized')
        return cls.__instance 
Example #8
Source File: cmds.py    From knob with MIT License 6 votes vote down vote up
def lmpCallback(self, lmp_packet, sendByOwnDevice, src, dest, timestamp):
                eth_header = dest + src + "\xff\xf0"
                meta_data  = "\x00"*6 if sendByOwnDevice else "\x01\x00\x00\x00\x00\x00"
                packet_header = "\x19\x00\x00" + p8(len(lmp_packet)<<3 | 7)

                packet = eth_header + meta_data + packet_header + lmp_packet
                packet += "\x00\x00" # CRC
                length = len(packet)
                ts_sec =  timestamp.second + timestamp.minute*60 + timestamp.hour*60*60
                ts_usec = timestamp.microsecond
                pcap_packet = struct.pack('@ I I I I', ts_sec, ts_usec, length, length) + packet
                try:
                    self.wireshark_process.stdin.write(pcap_packet)
                    self.wireshark_process.stdin.flush()
                    log.debug("LmpMonitorController._callback: done")
                except IOError as e:
                    log.warn("LmpMonitorController._callback: broken pipe. terminate.")
                    self.killMonitor() 
Example #9
Source File: win32.py    From multibootusb with GNU General Public License v2.0 6 votes vote down vote up
def ZapMBRGPT(self, disk_size, sector_size, add1MB):
        self.assert_physical_drive()
        # Implementation borrowed from rufus: https://github.com/pbatard/rufus
        num_sectors_to_clear \
            = (add1MB and 2048 or 0) + self.MAX_SECTORS_TO_CLEAR
        zeroBuf = b'\0' * sector_size
        for i in range(num_sectors_to_clear):
            self.WriteFile(zeroBuf)
        offset = disk_size - self.MAX_SECTORS_TO_CLEAR * sector_size
        win32file.SetFilePointer(self.h, offset, win32con.FILE_BEGIN)
        for i in range(num_sectors_to_clear):
            self.WriteFile(zeroBuf)
        # We need to append paddings as CREATE_DISK structure contains a union.
        param = struct.pack('<IIIHH8s',
                            winioctlcon.PARTITION_STYLE_MBR, 0xdeadbeef,
                            0,0,0,b'abcdefgh')
        win32file.DeviceIoControl(
            self.h, winioctlcon.IOCTL_DISK_CREATE_DISK, param, 0, None) 
Example #10
Source File: vachat.py    From The-chat-room with MIT License 6 votes vote down vote up
def run(self):
        while True:
            try:
                self.sock.connect(self.ADDR)
                break
            except:
                time.sleep(3)
                continue
        print("AUDIO client connected...")
        self.stream = self.p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK)
        while self.stream.is_active():
            frames = []
            for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
                data = self.stream.read(CHUNK)
                frames.append(data)
            senddata = pickle.dumps(frames)
            try:
                self.sock.sendall(struct.pack("L", len(senddata)) + senddata)
            except:
                break 
Example #11
Source File: structure.py    From smbprotocol with MIT License 6 votes vote down vote up
def __init__(self, size=None, **kwargs):
        """
        [MS-DTYP] 0.0 2017-09-15

        2.3.3 FILETIME
        The FILETIME structure is a 64-it value that represents the number of
        100 nanoseconds intervals that have elapsed since January 1, 1601 UTC.
        This is used to convert the FILETIME int value to a native Python
        datetime object.

        While the format FILETIME is used when communicating with the server,
        this type allows Python code to interact with datetime objects natively
        with all the conversions handled at pack/unpack time.

        :param size: Must be set to None or 8, this is so we can check/override
        :param kwargs: Any other kwarg to be sent to Field()
        """
        if not (size is None or size == 8):
            raise InvalidFieldDefinition("DateTimeField type must have a size "
                                         "of 8 not %d" % size)
        super(DateTimeField, self).__init__(size=8, **kwargs) 
Example #12
Source File: cmds.py    From knob with MIT License 6 votes vote down vote up
def hciCallback(self, record):
                hcipkt, orig_len, inc_len, flags, drops, recvtime = record

                dummy = "\x00\x00\x00"      # TODO: Figure out purpose of these fields
                direction = p8(flags & 0x01)
                packet = dummy + direction + hcipkt.getRaw()
                length = len(packet)
                ts_sec =  recvtime.second #+ timestamp.minute*60 + timestamp.hour*60*60 #FIXME timestamp not set
                ts_usec = recvtime.microsecond
                pcap_packet = struct.pack('@ I I I I', ts_sec, ts_usec, length, length) + packet
                try:
                    self.wireshark_process.stdin.write(pcap_packet)
                    self.wireshark_process.stdin.flush()
                    log.debug("HciMonitorController._callback: done")
                except IOError as e:
                    log.warn("HciMonitorController._callback: broken pipe. terminate.")
                    self.killMonitor() 
Example #13
Source File: structure.py    From smbprotocol with MIT License 6 votes vote down vote up
def pack(self):
        """
        Packs the field value into a byte string so it can be sent to the
        server.

        :param structure: The message structure class object
        :return: A byte string of the packed field's value
        """
        value = self._get_calculated_value(self.value)
        packed_value = self._pack_value(value)
        size = self._get_calculated_size(self.size, packed_value)
        if len(packed_value) != size:
            raise ValueError("Invalid packed data length for field %s of %d "
                             "does not fit field size of %d"
                             % (self.name, len(packed_value), size))

        return packed_value 
Example #14
Source File: TCP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def send(self, channel_type, message, additional_data):
		if channel_type == common.CONTROL_CHANNEL_BYTE:
			transformed_message = self.transform(self.encryption, common.CONTROL_CHANNEL_BYTE+message, 1)
		else:
			transformed_message = self.transform(self.encryption, common.DATA_CHANNEL_BYTE+message, 1)

		common.internal_print("{0} sent: {1}".format(self.module_short, len(transformed_message)), 0, self.verbosity, common.DEBUG)

		# WORKAROUND?!
		# Windows: It looks like when the buffer fills up the OS does not do
		# congestion control, instead throws and exception/returns with
		# WSAEWOULDBLOCK which means that we need to try it again later.
		# So we sleep 100ms and hope that the buffer has more space for us.
		# If it does then it sends the data, otherwise tries it in an infinite
		# loop...
		while True:
			try:
				return self.comms_socket.send(struct.pack(">H", len(transformed_message))+transformed_message)
			except socket.error as se:
				if se.args[0] == 10035: # WSAEWOULDBLOCK
					time.sleep(0.1)
					pass
				else:
					raise 
Example #15
Source File: DNS.py    From XFLTReaT with MIT License 6 votes vote down vote up
def do_changesettings(self, additional_data):
		message = struct.pack("<HHHH", self.settings[4], self.settings[0], self.settings[1], self.settings[3])
		self.send(common.CONTROL_CHANNEL_BYTE, self.CONTROL_TUNEME+message, additional_data)

		if (self.record_list[self.settings[4]][0] == "CNAME"):
			self.recordtype = self.settings[5]
		else:
			self.recordtype = self.record_list[self.settings[4]][0]
		self.RRtype_num = self.DNS_proto.reverse_RR_type_num(self.recordtype)
		self.upload_encoding_class = self.upload_encoding_list[self.settings[0]]
		self.download_encoding_class = self.download_encoding_list[self.settings[1]]

		self.qMTU = self.DNS_proto.reverse_RR_type("A")[4](self.settings[2]-1, self.hostname, 3, self.upload_encoding_class)
		self.set_mtu_ugly(self.DNS_proto.reverse_RR_type(self.recordtype)[4](self.settings[3]-1, "", 3, self.download_encoding_class))

		return

	# function used for autotuning, crafting tune type requests, sending the 
	# packets then checking the answer.
	# return
	# True: if the packet went thru and the answer is correct. Encoding, size
	# 	were correct
	# False: packet failed. Too big or crippled packet, wrong encoding etc. 
Example #16
Source File: encoding.py    From XFLTReaT with MIT License 6 votes vote down vote up
def decode(self, text):
		if len(text) % 5:
			return None

		decoded_text = ""
		text = text.replace("{",".")
		for i in range(0, len(text)/5):
			encoded_text = text[i*5:(i+1)*5]

			N0 = ord(encoded_text[0]) - 33
			N1 = ord(encoded_text[1]) - 33
			N2 = ord(encoded_text[2]) - 33
			N3 = ord(encoded_text[3]) - 33
			N4 = ord(encoded_text[4]) - 33
			c = N0*52200625 + N1*614125 + N2*7225 + N3*85 + N4

			decoded_text += struct.pack(">I", c)
		return decoded_text 
Example #17
Source File: interface.py    From XFLTReaT with MIT License 6 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 #18
Source File: interface.py    From XFLTReaT with MIT License 6 votes vote down vote up
def freebsd_tun_alloc(self, dev, flags):
		try:
			sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			ifr = struct.pack('<16si', 'tun', 0)
			self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
			self.iface_name = self.iface_name.rstrip("\x00")

			buff = array.array('c', dev+"\x00")
			caddr_t, _ = buff.buffer_info()
			ifr = struct.pack('16sP', self.iface_name, caddr_t);

			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
			tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
			self.iface_name = dev

		except IOError as e:
			print e
			common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
			sys.exit(-1)

		return tun 
Example #19
Source File: interface.py    From XFLTReaT with MIT License 6 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 #20
Source File: interface.py    From XFLTReaT with MIT License 5 votes vote down vote up
def lin_set_mtu(self, dev, mtu):
		s = socket.socket(type=socket.SOCK_DGRAM)
		try:
			ifr = struct.pack('<16sH', dev, mtu) + '\x00'*14
			fcntl.ioctl(s, self.IOCTL_LINUX_SIOCSIFMTU, ifr)
		except Exception as e:
			common.internal_print("Cannot set MTU ({0}) on interface".format(mtu), -1)
			sys.exit(-1)

		return 
Example #21
Source File: addresses.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def getSubnet(ipaddr, netmask):
    try:
        val1 = struct.unpack("!I", socket.inet_aton(ipaddr))[0]
        nm = struct.unpack("!I", socket.inet_aton(netmask))[0]
        res = val1 & nm
        return socket.inet_ntoa(struct.pack('!I', res))
    except Exception:
        return None 
Example #22
Source File: interface.py    From XFLTReaT with MIT License 5 votes vote down vote up
def lin_tun_alloc(self, dev, flags):
		try:
			tun = os.open(Interface.LINUX_CLONEDEV, os.O_RDWR|os.O_NONBLOCK, 0)
			ifr = struct.pack('16sH', dev, flags)
			fcntl.ioctl(tun, self.IOCTL_LINUX_TUNSETIFF, ifr)

		except IOError:
			common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
			sys.exit(-1)

		return tun 
Example #23
Source File: interface.py    From XFLTReaT with MIT License 5 votes vote down vote up
def mac_set_mtu(self, dev, mtu):
		s = socket.socket(type=socket.SOCK_DGRAM)
		try:
			ifr = struct.pack('<16sH', self.iface_name, 1350)+'\x00'*14
			fcntl.ioctl(s, self.IOCTL_MACOSX_SIOCSIFMTU, ifr)
		except Exception as e:
			common.internal_print("Cannot set MTU ({0}) on interface".format(mtu), -1)
			sys.exit(-1)

		return 
Example #24
Source File: dns_proto.py    From XFLTReaT with MIT License 5 votes vote down vote up
def build_query(self, transaction_id, data, hostname, RRtype):
		flag = 0x0100 #0000 0010 0000 0000
		dns_header = struct.pack(">HHHHHH", transaction_id, flag, 1, 0, 0, 0)
		qhostname = self.hostname_to_hostnamebin(data+hostname)

		return dns_header + qhostname + struct.pack(">HH", RRtype, 1) 
Example #25
Source File: msch.py    From mindustry-modding with GNU General Public License v3.0 5 votes vote down vote up
def pack_utf8(string):
    b = bytes(string, "utf8")
    bl = pack(">h", len(b))
    return bl + b 
Example #26
Source File: ntfsea.py    From WSL-Distribution-Switcher with MIT License 5 votes vote down vote up
def generate(self):
		"""
		Generate an lxattrb entry using the currently set values.
		:return: Entry bytes.
		"""

		return struct.pack(lxattrb.structure, self.flags, self.version, self.mode, self.uid, self.gid, self.drive, 0, 0, 0, self.atime, self.mtime, self.ctime) 
Example #27
Source File: interface.py    From XFLTReaT with MIT License 5 votes vote down vote up
def freebsd_set_mtu(self, dev, mtu):
		s = socket.socket(type=socket.SOCK_DGRAM)
		try:
			ifr = struct.pack('<16sH', self.iface_name, mtu) + '\x00'*14
			fcntl.ioctl(s, self.IOCTL_FREEBSD_SIOCSIFMTU, ifr)
		except Exception as e:
			common.internal_print("Cannot set MTU ({0}) on interface".format(mtu), -1)
			sys.exit(-1)

		return 
Example #28
Source File: systemconfig_test.py    From macops with Apache License 2.0 5 votes vote down vote up
def testGetMACFromData(self):
    """Test _GetMACFromData."""
    mac_data = (0, 62, 225, 190, 73, 13)
    mac_str = '00:3e:e1:be:49:0d'
    buf = struct.pack('6B', *mac_data)
    self.assertEqual(mac_str, systemconfig._GetMACFromData(buf)) 
Example #29
Source File: addresses.py    From Paradrop with Apache License 2.0 5 votes vote down vote up
def incIpaddr(ipaddr, inc=1):
    """
        Takes a quad dot format IP address string and adds the @inc value to it by converting it to a number.

        Returns:
            Incremented quad dot IP string or None if error
    """
    try:
        val = struct.unpack("!I", socket.inet_aton(ipaddr))[0]
        val += inc
        return socket.inet_ntoa(struct.pack('!I', val))
    except Exception:
        return None 
Example #30
Source File: systemconfig_test.py    From macops with Apache License 2.0 5 votes vote down vote up
def testGetMACFromDataWithBadData(self):
    mac_data = (0, 62)
    buf = struct.pack('2B', *mac_data)
    with self.assertRaises(systemconfig.InterfaceError):
      systemconfig._GetMACFromData(buf)