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

2

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent explanation. Thank you a lot ! :) I suppose that I always have an IP address with the correct CIDR.
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"; 

2 Comments

My first solution works without any php, fiddle here: jsfiddle.net/rBL3D/80

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.