Peter
Peter Campbell Smith

Fangs and strings

Weekly challenge 272 — 3 June 2024

Week 272 - 3 Jun 2024

Task 1

Task — Defang IP address

You are given a valid IPv4 address. Write a script to return the defanged version of the given IP address. A defanged IP address replaces every period “.” with “[.]".

Examples


Example 1
Input: $ip = "1.1.1.1"
Output: "1[.]1[.]1[.]1"

Example 2
Input: $ip = "255.101.1.0"
Output: "255[.]101[.]1[.]0"

Analysis

I wonder why you would want to do that?

There isn't really much to analyse: if we can assume that the input is valid then the answer is barely even one line of Perl.

Of course, we might have been asked to check:

  • if the IP address is valid - ie contains 4 numbers in the range 0-255 separated by dots,
  • or if we're allowing subnet addresses, 1, 2 or 3 dot-separated numbers,
  • or if IP address is routable by the internet - so not 192.168.x.x or 10.x.x.x or 172.16.0.x,
  • or if IP address is associated with a name, eg bbc.co.uk,
  • or if IP address is v4 and not v6 - so not like fe80::2960:bb83:db18:8b4e.

But we weren't, so I didn't.

Try it 

Try running the script with any input:



example: 314.159.2.65

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 3 June 2024
use utf8;     # Week 272 - task 1 - Defang IP address
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

defang_ip_address('192.168.1.245');
defang_ip_address('0.0.0.0');
defang_ip_address('255.255.255.255');
defang_ip_address('192.168.1.20');

sub defang_ip_address {
    
    $_[0] =~ m|(\d+).(\d+).(\d+).(\d+)|;
    say qq{\nInput:  \$ip = "$_[0]"\nOutput: "$1\[.]$2\[.]$3\[.]$4"};
}

Output


Input:  $ip = "192.168.1.245"
Output: "192[.]168[.]1[.]245"

Input:  $ip = "0.0.0.0"
Output: "0[.]0[.]0[.]0"

Input:  $ip = "255.255.255.255"
Output: "255[.]255[.]255[.]255"

Input:  $ip = "192.168.1.20"
Output: "192[.]168[.]1[.]20"

The content of this website which has been created by
Peter Campbell Smith is hereby placed in the public domain