Ɛɔıs3
Ɛɔıs3

Reputation: 7853

Find the network address with IP address in jQuery

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

Upvotes: 0

Views: 1560

Answers (2)

billyonecan
billyonecan

Reputation: 20260

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)

Upvotes: 1

user3994654
user3994654

Reputation:

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"; 

Upvotes: 1

Related Questions