Stanley LEsniak
Stanley LEsniak

Reputation: 59

Trying to replace last 2 octets of ip address

I have the following ip address "192.168.2.65"

Is there a way to convert the last 2 octets to 0.

I found the following, but it only lets me replace the last one, i need to replace the last 2.

ip = 192.168.2.65
output='.'.join(ip.split('.')[:-1]+["0"])
print(output)

which gives me 192.168.2.0 and i would like to be 192.168.0.0

Upvotes: 0

Views: 1594

Answers (3)

PacketLoss
PacketLoss

Reputation: 5746

Dependant on the logic you are trying to apply.. if you are simply wanting to modify a string, the other answers are correct.

However, if you are looking to get the network address for the subnet an address resides in, you should handle the addresses correctly and use the ipaddress module.

This will assist in calculating the correct network & broadcast addresses, and allow you to check inclusions in networks etc.


import ipaddress

interface = IPv4Interface('192.168.2.35/255.255.0.0')

print(interface.network)

#192.168.0.0/16

print(interface.network.network_address)

#192.168.0.0

print(interface.network.broadcast_address)

#192.168.255.255

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521178

You could also use a regex based approach here:

ip = "192.168.2.65"
output = re.sub(r'\.\d+\.\d+$', '.0.0', ip)
print(output)   # prints 192.168.0.0

Upvotes: 0

Ngoc N. Tran
Ngoc N. Tran

Reputation: 1068

Index -1 means the last index. If you want to change two, change your index to -2.

output='.'.join(ip.split('.')[:-2]+["0", "0"])

Upvotes: 4

Related Questions