D
D
DDD2020-12-02 13:07:20
Python
DDD, 2020-12-02 13:07:20

How to convert CIDR prefix to netmask?

Please help solve this problem, you need to add the code so that the entered mask, together with the ip, for example, 192.168.75.2/24 or 192.168.75.2/3, is converted to 192.168.75.2 255.255.255.0 and the like
through a bunch of ifs, somehow I don’t really want to do this I found this code on the internet but it doesn't seem to work.

import socket
import struct

def cidr_to_netmask(cidr):
    network, net_bits = cidr.split('/')
    host_bits = 32 - int(net_bits)
    netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
    return network, netmask

Below is what I posted, please help me finish it
import struct
import socket


print ("enter IP/Mask: ")
StatIP = input()
print ("enter Gateway: ")
StatGA = input()
net_bits = StatIP.split('/')

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
galaxy, 2020-12-02
@Kiberchief

I found this code but it doesn't work

Why did you decide that it is not working?

M
MrPurrPurr, 2020-12-02
@MrPurrPurr

import ipaddress

StatIP =  input("enter IP/Mask: ")
cidr = ipaddress.ip_interface(StatIP)
print(cidr.ip, cidr.netmask)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question