Monday, May 8, 2017

How to convert IP address from Decimal to Binary using Python

class IPAddress:
    ip_address=""
    def __init__(self, string):
        #validate IP address
        valid_ip = True;
        invalid_reason = ""
        add_arr = string.split(".")
        add_int_arr = []
        if len(add_arr) != 4:
            valid_ip = False
            invalid_reason = "Invalid IP address: Length of IP is not correct"
        for add in add_arr:
            try:
                add_int_arr.append(int(add))
            except ValueError:
                valid_ip = False
                invalid_reason = "Invalid IP address: The input contains none number characters"

        if valid_ip == True:
            first_add, second_add, third_add, fourth_add = add_int_arr
            if (first_add < 1) or (first_add > 255):
                valid_ip = False
                invalid_reason = "Invalid IP address: The input IP address contains invalid number"
            for add in (second_add, third_add, fourth_add):
                if (add < 0) or (add > 255):
                    print add
                    valid_ip = False
                    invalid_reason = "Invalid IP address: The input IP address contains invalid number"

        if valid_ip == True:
            self.ip_address=string
        else:
            assert (valid_ip), invalid_reason
    def IPDec2Bin(self):
        ip_arr = self.ip_address.split(".")
        ip_bin_str = ""
        for ip in ip_arr:
            ip_bin_str = ip_bin_str + "{:08b}".format(int(ip)) + "."
        return ip_bin_str[0:len(ip_bin_str)-1]
#application script
IP = IPAddress("103.88.17.23")
final_ip_bin_str =IP.IPDec2Bin()
print "{:<15} {:<45}".format("IP address", "Binary")
print "{:<15} {:<45}".format(IP.ip_address, final_ip_bin_str)

No comments:

Post a Comment