0

Suppose we have an IP address such as: 192.168.1.1/24, how to find the network address from this address?

I tried to cut out the IP address to replace the last character by 0, but it isn't working.

$('.ip').val().replace($('.ip').val().split('/')[0].split('.')[3], 0);

Where $('.ip') is the selector of an input whose class name is ip.

Returns 092.168.1.1/24. The expected result is rather this : 192.168.1.0/24

w3spi
  • 4,380
  • 9
  • 47
  • 80

2 Answers2

1

Using a third party service might be your best option:

$(document).ready(function () {
    $.getJSON("http://jsonip.com/?callback=?", function (data) {
        var ip = data.ip;
    });
});

Something else you can try is using Jquery's ajax function to get the content of a PHP file you create on your server, and in that php file you echo the user's IP address using

$ip=$_SERVER['REMOTE_ADDR'];
echo "IP address= $ip"; 
  • Sources: http://stackoverflow.com/a/19953367/3994654 http://www.plus2net.com/php_tutorial/php_ip.php –  Jun 29 '15 at 12:49
  • My first solution works without any php, fiddle here: https://jsfiddle.net/rBL3D/80/ –  Jun 29 '15 at 13:05
1

The following will give you the desired result:

$('.ip').val(function(_, value) {
   return value.replace(/\d+(\/\d+)$/, '0$1');
});

\d+(\/\d+)$ replaces one digit or more, which is followed by a forward slash (/) and one digit it more (at the end of the given string).

0$1 is the replacement, so 0 followed by the value which matched the expression between () (in the example this is /24)

Just a side note, this has no concept of CIDR notation (ie. if the CIDR was changed the result would be the same - it's a simple string replacement)

billyonecan
  • 20,090
  • 8
  • 42
  • 64
  • Excellent explanation. Thank you a lot ! :) I suppose that I always have an IP address with the correct CIDR. – w3spi Jun 29 '15 at 14:28