Git Product home page Git Product logo

ipaddress's People

Contributors

seancfoley avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ipaddress's Issues

eclipse project kept showing error

Hi

I kept getting the following error when import ipaddress-5.0.2.jar to my eclipse project.
The type java.lang.String cannot be resolved. It is indirectly referenced from required .class files

Could you please provide some info how I can resolve this issue?

My eclipse version is Version: Oxygen.3a Release (4.7.3a) Build id: 20180405-1200
attached my build path and build java version
Screen Shot 2019-07-22 at 9 38 09 PM

Screen Shot 2019-07-22 at 9 35 47 PM

If I compile in the command line, it's compiled fine. It seems like only happens in eclipse.

Thanks

Hostname ipAddress bug?

Greetings,

First of all thanks for providing awesome work. I hope still you continue on the project.

I have encountered a weird thing while using the library you provided. See the following:

HostName hostName = new HostName("23.23.43");
String host = hostName.getHost(); // host = 23.23.0.43

I'm not sure whether this is expected behavior or a problem. I would expect to have either null string or some sort of exception claiming illegal argument.

I debug a bit and see that host value in HostName objectis "23.23.43" it is converted into valid IP during getHost() method.

If you can clarify (or solve) it would be appreciated!

Best regards,
Alperen

Unexpected result with IPv4Address.toSequentialRange method

The following ip: 127.0.0.158 (2130706590 in Integer form), with a subnet mask of 24.

When i create a range of ips with toSequentialRange() i don't get a complete range of ips. I get a IPv4AddressSeqRange with 1 IP inside it. (127.0.0.158 -> 127.0.0.158), when i expect it to be (127.0.0.0 -> 127.0.0.250), calculated with: http://jodies.de/ipcalc?host=130.225.157.76&mask1=24&mask2=

When i create the ip-range with toZeroHost and toMaxHost the range comes out as expected.

Using scala, jdk11, and v5.1.0 or 5.0.2 of this lib.

Code to reproduce:

    val ip = 2130706590
    val mask = 24
    val ipAdd = new IPv4Address(ip, mask)

    println(ipAdd)

    val ipRange = ipAdd.toSequentialRange
    val ipRange2 = ipAdd.toZeroHost.toSequentialRange(ipAdd.toMaxHost)

    if (ipRange != ipRange2) {
      println(s"$ipRange not the same as $ipRange2")
    }

same thing happens with 194.105.145.69/31 where the range is still just 1 IP, but i expect it to be 194.105.145.68 -> 194.105.145.69. (Again, using toZeroHost and toMaxHost works)

Is this a bug, or is my expectation of toSequentialRange wrong?

Iterate over network interfaces

hi! first of all, thank you for your wonderful API, you rock! =)

I didn't find a "native" way how to iterate over network interfaces for a box.
I came up with a code like

IPAddressGenerator generator = new IPAddressGenerator();

List<IPAddress> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
        .stream()
        .flatMap(ni -> Collections.list(ni.getInetAddresses()).stream())
        .map(generator::from)
        .collect(Collectors.toList());

but it looks overkill for me. Do you have a simpler way?
thanks!

iterate IPAddress.getIterable is taking more than 20 seconds

Note: This is not a bug just performance issue.

Following method return list of IP address from wild card string 10.*.*.* and i have added the println statements to know the time it is taking to iterate IPAddress ,

public List<String> getIPAddressListFromWildCard(String hostAddress)throws AddressStringException,IncompatibleAddressException {
		List<String> listIPAddress = new ArrayList<String>();
		IPAddressString ipAddressString = new IPAddressString("10.*.*.*");
		try {
			IPAddress hostAddressObj = ipAddressString.toAddress();
			System.out.println("count: "+hostAddressObj.getCount());
			System.out.println("date at before start iterator "+new Date());
			for(IPAddress address:hostAddressObj.getIterable()) {
				listIPAddress.add(address.toSubnetString());
			}
			System.out.println("date at after completion of iterator "+new Date());
		} catch (AddressStringException | IncompatibleAddressException e) {
			throw e;
		}
		return listIPAddress;
	}

Response

count: 16777216
date at before start iterator Mon Sep 03 11:54:53 IST 2018
date at after completion of iterator Mon Sep 03 11:55:19 IST 2018

Here to iterate IPAddress, it is taking more than 20 seconds.Is there any way to get the list of IP addresses without iterating.I just need list of IP addresses not the IPAddress object of each IP .

extract ip from mixed ip/mask specification

IPAddressString ipas = new IPAddressString("10.1.2.3/24");
ipas.getAddress(); // returns "10.1.2.0"

Is there a way to retrieve the "original/unmasked" ip address?
ipas.getUnmaskedAddress() -> "10.1.2.3"

I would like to parse strings representing a ip/mask combination.
Maybe I'm missing something.

IPv6 upper & lower not being returned accurately.

We noticed that in some cases the getUpper() & getLower() for ipv6 is producing unexpected results.

Examples:
Case 1: this works as expected.

IPv6Address rangeString1 = new IPAddressString("2001:470:7:a00::/56").getAddress().toIPv6()
rangeString1.getUpper().toAddressString() //produces 2001:470:7:aff:ffff:ffff:ffff:ffff/56
rangeString1.getLower().getSection().toString() //produces 2001:470:7:a00:0:0:0:0/56

Case 2: this doesn't work as expected. Doesn't produce upper & lower bounds

IPv6Address rangeString = new IPAddressString("2001:470:7:a00::/53").getAddress().toIPv6();
rangeString.getLower().getSection().toString() // produces 2001:470:7:a00:0:0:0:0/53 (as expected)
rangeString.getUpper().getSection().toString() // produces 2001:470:7:a00:0:0:0:0/53 which I believe to be wrong 

Thanks

Throw ArrayIndexOutOfBoundsException with a prefix for single block

On version 4.2.0, the following code will throw ArrayIndexOutOfBoundsException:4

IPAddress ipAddress = (new IPAddressString("1.2.3.4")).toAddress().assignPrefixForSingleBlock(); ipAddress.toPrefixBlock();

I am not family with network terms so I don't know if it is valid case.

Get Network Class

Hi,

Absolutely loving this API. I just want to find out, is there a way to get the Network class of a given CIDR? Something in the lines of:

IPAddress addr = new IPAddressString( "10.0.0.0/8").getAddress();
System.out.println(addr.getNetworkClass()) // Prints A and in other scenarios B, C or D

IPv6 CIDR block is created for Hex IPv4 IP ranges

I have two Hex IPv4 ranges from which i want to create cidr blocks.
StartIP - 0000000000000000000000000A000000 (10.0.0.0)
EndIP - 0000000000000000000000000AFFFFFF (10.255.255.255)

IPAddress start = 
new IPAddressString("0000000000000000000000000A000000").getAddress();

IPAddress end = 
new IPAddressString("0000000000000000000000000AFFFFFF").getAddress();

IPAddress cidrs[] = start.toSequentialRange(end).spanWithPrefixBlocks();

//output of cidrs[] = [::a00:0/104]

It is giving ::a00:0/104 block for IPV4 range . Instead it should give 10.0.0.0/8 block.

Ipv6 address subnet

hi, i have an ipv6 subnet, and i have to get the list of addresses of the subnets contained.
In this case I get only one value but in reality I should get more (ex: 2a03:b7c0:230:33::/64 , 2a03:b7c0:230:34::/64, etc.).
it's correct?
thank you

     IPAddress subnet = new IPAddressString("2a03:b7c0:0230:0033::").getAddress();
        subnet = subnet.setPrefixLength(53);
        IPAddress newSubnets = subnet.setPrefixLength(64, false);
        Iterator<? extends IPAddress> iterator = newSubnets.prefixBlockIterator();
        while (iterator.hasNext()) {
            system.out.print(iterator.next().toInetAddress().getHostAddress());
        }

IPAddressString.toAddress() doesn't fail as expected with an incomplete IPv4 address.

Current Behavior:
Incomplete IPv4 address strings don't fail to parse as expected when put in an IPAddressString and converted to an address with toAddress(). For example, the string "192.168" will be parsed as "192.0.0.168", and "192.168.1" will be parsed as "192.168.0.1", instead of throwing an exception.

Expected Behavior:
An exception is thrown.

Reproduction:
@test
void reproduction() throws AddressStringException {
String input = "192.168";
IPAddressString ipAddressString = new IPAddressString(input);
IPAddress ipAddress = ipAddressString.toAddress();
assertEquals("192.0.0.168", ipAddress.toCanonicalString());
}

Versions:
Library version: 5.3.1
Java version: AdoptOpenJDK 11.0.6

Version 1.0.0 jar not working on jdk 1.7

Hello,
We are using java 7 on our systems and need v1.0.0 library for our IPv6 related requirements.
While trying to use the library I got the following error:
Exception in thread "main" java.lang.UnsupportedClassVersionError: inet/ipaddr/IPAddressString : Unsupported major.minor version 52.0

While trying to build the same using ant using task "create class jar", no files in ipv4, ipv6 and subdirectories in format folder are compiled and packaged. I get the following error during compilation:
`compile:
[javac] /home/IPAddress/IPAddress/build.xml:47: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds

[javac] Compiling 1 source file to /home/IPAddress/IPAddress/bin

[javac] warning: [options] bootstrap class path not set in conjunction with -source 1.7

[javac] /home/IPAddress/IPAddress/src/inet/ipaddr/IPAddressSection.java:1051: error: local variable skipThis is accessed from within inner class; needs to be declared final

[javac] 				boolean done = skipThis;

[javac] 				               ^

[javac] /home/IPAddress/IPAddress/src/inet/ipaddr/IPAddressSection.java:1085: error: local variable skipThis is accessed from within inner class; needs to be declared final

[javac] 				if(skipThis) {

[javac] 				   ^

[javac] 2 errors

[javac] 1 warning

[javac] Compile failed; see the compiler error output for details.

`

Kindly help.
Thank you!

Ipv6 Increment issue with segment-2

Hi SeancFoley,
Maven jar Version : 5.3.1
i was trying to get two subnets of mask 25 from IPv6 CIDR "7c40:​100::/24".
which will result this ("7c40:​100::/25", "7c40:180::/25")

I am able to get the first subnet of 25 using addr.getNetworkSection(25)
And for second subnet of same mask i.e 25 using addr.getNetworkSection(25).getUpper().increment(1) which is throwing Below mentioned exception

Exception in thread "main" inet.ipaddr.AddressValueException: 1, IP Address error: exceeds address size
at inet.ipaddr.format.standard.AddressDivisionGrouping.checkOverflow(AddressDivisionGrouping.java:1209)
at inet.ipaddr.ipv6.IPv6AddressSection.increment(IPv6AddressSection.java:1333)
at inet.ipaddr.ipv6.IPv6AddressSection.increment(IPv6AddressSection.java:99)
at com.ipam.mgmt.util.IpBlockUtils.getSubnet(IpBlockUtils.java:157)
at com.ipam.mgmt.util.IpBlockUtils.main(Unknown Source)

Doing some debugging i do found the root cause of the problem and solution for it too.

ROOT Cause: in IPv6AddressSection.java while checking the checkOverflow condition exception is thrown and reason why it throws exception is it get MAX_VALUES_BY_SEGMENT for segment 2 as -1

Solution : The IPv6AddressSection.java contains a BigInteger Array as pasted below
private static final BigInteger MAX_VALUES_BY_SEGMENT[] = {
BigInteger.ZERO,
BigInteger.valueOf(IPv6Address.MAX_VALUE_PER_SEGMENT),
BigInteger.valueOf(0xffffffff),
BigInteger.valueOf(0xffffffffffffL),
BigInteger.valueOf(1).shiftLeft(16 * 4).subtract(BigInteger.ONE),
BigInteger.valueOf(1).shiftLeft(16 * 5).subtract(BigInteger.ONE),
BigInteger.valueOf(1).shiftLeft(16 * 6).subtract(BigInteger.ONE),
BigInteger.valueOf(1).shiftLeft(16 * 7).subtract(BigInteger.ONE),
BigInteger.valueOf(1).shiftLeft(16 * 8).subtract(BigInteger.ONE),
};

The implementation of "BigInteger.valueOf(0xffffffff)" at index 3 is returning -1 whereas it was supposed to return "4294967295".
which can be fixed by correcting the Value at 3rd Index by adding L as shown below
"BigInteger.valueOf(0xffffffff)" -> BigInteger.valueOf(0xffffffffL)

"BigInteger.valueOf(0xffffffff)" gives -1
"BigInteger.valueOf(0xffffffffL)" gives 4294967295

Please fix it and provide new Hotfix for it.

IPv6Address with prefix length and zone to Inet6Address conversion issue

When an ipv6 address with a zone and a associated prefix length is converted to an JRE Inet6Address null is returned because the JRE can't parse the subnet mask. E.g. when an address like this is constructed:
"fe80::%eth13/64"

Then an exception is thrown here because the zone is not numeric (eth13):
https://github.com/seancfoley/IPAddress/blob/master/IPAddress/src/inet.ipaddr/inet/ipaddr/ipv6/IPv6Address.java#L1781
and converted to a normalized string which is "fe80:0:0:0:0:0:0:0%eth13/64" which will result in an UnknownHostException from the JRE because of following error:
"java.net.UnknownHostException: no such interface eth13/64"

IPAddress contains error?

I use this library to check whether a given search ip is in a cird network. But I am confused the result.
202.203.208.33 is not in 202.203.0.0/15 ?

image

I used the following dependency in my pom.xml.

		<dependency>
			<groupId>com.github.seancfoley</groupId>
			<artifactId>ipaddress</artifactId>
			<version>5.1.0</version>
		</dependency>
The relevant code is below
  public List<Acl> search(String searchIp) {
    QueryWrapper<Acl> queryWrapper = new QueryWrapper<Acl>();
    List<Acl> allAcls = recordMapper.selectList(queryWrapper);
    IPAddress searchIPAddress = new IPAddressString(searchIp).getAddress();
    List<Acl> results = allAcls.stream().filter(acl -> {
      IPAddress address =
          new IPAddressString(String.format("%s/%s", acl.getIp(), acl.getCidr())).getAddress();
      return address.contains(searchIPAddress);
    }).collect(Collectors.toList());
    return results;
  }

allowLeadingZeros too strict?

val Optionsv4 = new IPv4AddressStringParameters(
  false,
  false,
  false,
  RangeParameters.NO_RANGE,
  false,
  false,
  false,
  false,
  false,
  false,
  null)

val Optionsv6 = new IPv6AddressStringParameters(
  true,
  false,
  false,
  false,
  new IPAddressStringParameters.Builder().toParams,
  false,
  false,
  RangeParameters.NO_RANGE,
  false,
  false,
  null)

val Options = new IPAddressStringParameters(
  false,
  false,
  false,
  false,
  false,
  false,
  false,
  true,
  true,
  Optionsv4,
  Optionsv6)


new IPAddressString("1.2.0.1", Options).toAddress()

I expected this to work but it throws

inet.ipaddr.AddressStringException: 1.2.0.1 IP Address error: segment value starts with zero
	at inet.ipaddr.format.validate.Validator.validateAddress(scratch_198:622)
	at inet.ipaddr.format.validate.Validator.validateIPAddress(scratch_198:166)
	at inet.ipaddr.format.validate.Validator.validateAddress(scratch_198:134)
	at inet.ipaddr.IPAddressString.validate(scratch_198:453)
	at inet.ipaddr.IPAddressString.validate(scratch_198:402)
	at inet.ipaddr.IPAddressString.toAddress(scratch_198:765)
	at #worksheet#.get$$instance$$res0(scratch_198:46)
	at #worksheet#.#worksheet#(scratch_198:70)

I believe that there is a problem with allowLeadingZeros option because when it is set to true this example no longer throws. However, this has a side-effect of allowing addresses like 01.02.0.01 which I do not want.

Get index of address in network/mask

I looked through the API and don't see anything specifically available to quickly do this, though I'm sure it is possible via the low-level (fast) math or high-level (slow) iterators. Using your API and a given subnet/mask (IPv4AddressNetwork class?), how would you recommend getting hold of an actual subnet (if possible) which holds this address and the index (again, if possible) of that address within the subnet?

As a simple contrived example:

Subnet/Mask = 192.168.1.0/24
Address = 192.168.4.20
Expected answers:  1) 192.168.4.0/24
                   2) 19

I'm quite aware that the example address does not exist inside this example subnet. This was done on purpose to see if the API has a way to give you a set of the possible (i.e scale range) subnets given a mask, and then use those possible subnets to determine which one would include the simple address (note no provided mask on purpose).

It may be that the simplest approach here is the bitwise math, but I wanted to see if your API has some hidden features I didn't notice. If possible, I'd also be interested in having the index be dependent upon whether you wanted to consider just the host range.

Thanks!

OSGi Support

It would be nice when the jar would contain OSGi metadata so we could directly consume it via maven central without doing any wrapping.
I have seen this project uses ant to build. I'm not familiar with ant (only gradle/maven) so I can't provide a pull request for generating OSGi metdata but I can guide you into the right direction.
First I would recommend BND - BND is a tool which automatically generates a MANIFEST.MF containing all the necessary OSGi metdata based on the compiled *.class files. BND can be used with gradle, maven and ant to analyze the class files and generate the corresponding MANIFEST.MF based on them and a instructions file (e.g. bnd.bnd). This bnd.bnd file tells bnd what it should do.
In your case:
Bundle-SymbolicName: com.github.seancfoley.ipaddress
Export-Package: inet.ipaddr.*

would be probably enough.

Here I have also found a BND ant example: https://groups.google.com/forum/#!topic/bndtools-users/UgQ9bmoU4Eg

The final MANIFEST.MF should look roughly something like that:

Manifest-Version: 1.0
Automatic-Module-Name: com.github.seancfoley.ipaddress
Bnd-LastModified: 1581504821138
Bundle-ManifestVersion: 2
Bundle-Name: com.github.seancfoley.ipaddress
Bundle-SymbolicName: com.github.seancfoley.ipaddress
Bundle-Version: 5.2.1
Created-By: 1.8.0_202-ea (Oracle Corporation)
Export-Package: inet.ipaddr;uses:="inet.ipaddr.format,inet.ipaddr.form
 at.standard,inet.ipaddr.format.string,inet.ipaddr.format.util,inet.ip
 addr.format.util.sql,inet.ipaddr.format.validate,inet.ipaddr.ipv4,ine
 t.ipaddr.ipv6,inet.ipaddr.mac";version="5.2.1",inet.ipaddr.format;use
 s:="inet.ipaddr,inet.ipaddr.format.standard,inet.ipaddr.format.string
 ,inet.ipaddr.format.util";version="5.2.1",inet.ipaddr.format.large;us
 es:="inet.ipaddr,inet.ipaddr.format,inet.ipaddr.format.string,inet.ip
 addr.format.util";version="5.2.1",inet.ipaddr.format.standard;uses:="
 inet.ipaddr,inet.ipaddr.format,inet.ipaddr.format.string,inet.ipaddr.
 format.util,inet.ipaddr.format.validate";version="5.2.1",inet.ipaddr.
 format.string;uses:="inet.ipaddr,inet.ipaddr.format.util";version="5.
 2.1",inet.ipaddr.format.util;uses:="inet.ipaddr,inet.ipaddr.format,in
 et.ipaddr.format.standard,inet.ipaddr.format.string,inet.ipaddr.forma
 t.util.sql";version="5.2.1",inet.ipaddr.format.util.sql;uses:="inet.i
 paddr.format.string,inet.ipaddr.format.util";version="5.2.1",inet.ipa
 ddr.format.validate;uses:="inet.ipaddr,inet.ipaddr.format,inet.ipaddr
 .format.standard,inet.ipaddr.mac";version="5.2.1",inet.ipaddr.ipv4;us
 es:="inet.ipaddr,inet.ipaddr.format,inet.ipaddr.format.standard,inet.
 ipaddr.format.string,inet.ipaddr.format.util,inet.ipaddr.ipv6";versio
 n="5.2.1",inet.ipaddr.ipv6;uses:="inet.ipaddr,inet.ipaddr.format,inet
 .ipaddr.format.standard,inet.ipaddr.format.string,inet.ipaddr.format.
 util,inet.ipaddr.ipv4,inet.ipaddr.mac";version="5.2.1",inet.ipaddr.ma
 c;uses:="inet.ipaddr,inet.ipaddr.format,inet.ipaddr.format.standard,i
 net.ipaddr.format.string,inet.ipaddr.format.util,inet.ipaddr.ipv6";ve
 rsion="5.2.1"
Import-Package: inet.ipaddr,inet.ipaddr.format,inet.ipaddr.format.larg
 e,inet.ipaddr.format.standard,inet.ipaddr.format.string,inet.ipaddr.f
 ormat.util,inet.ipaddr.format.util.sql,inet.ipaddr.format.validate,in
 et.ipaddr.ipv4,inet.ipaddr.ipv6,inet.ipaddr.mac
Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=1.8))"
Tool: Bnd-4.3.1.201911131708

It is possible to simply "hardcode" the manifest additions like that but that would mean that if packages are added you would have to manually maintain that hardcoded manifest too. Some stuff listed above is also optional and only produced because bnd produces "super correct" manifests.

it converted a err cidr when start ip equals end ip or cidr contains a single Ip

for example:

public static List<String> rangeToCIDR(String start, String end) {
        IPAddressString startIpAddressString = new IPAddressString(start);
        IPAddressString endIpAddressString = new IPAddressString(end);
        IPAddress startIpAddress = startIpAddressString.getAddress();
        IPAddress endIpAddress = endIpAddressString.getAddress();
        IPAddressSeqRange range = startIpAddress.toSequentialRange(endIpAddress);
        IPAddress[] result = range.spanWithPrefixBlocks();
        return Arrays.stream(result).map(Address::toString).collect(Collectors.toList()).toString();
}

examp1:

start ip: 77.220.115.0
end id: 77.220.115.0
when test, it shows [77.220.115.0], but correct result is [77.220.115.0/32]

exmap2

start ip: 77.220.115.0
end id: 77.220.116.64
when test, it shows [77.220.115.0/24, 77.220.116.0/26, 77.220.116.64], but correct result is [77.220.115.0/24, 77.220.116.0/26, 77.220.116.64/32];

is it a bug? thks

getHostAddress() should belong to IPAddress, not IPAddressString

1 - It loses concrete type after conversion:

IPv4Address ip = new IPv4Address(123456, 24);
ip.toAddressString().getHostAddress().isPrivate(); // oops

2 - It's unnecessary conversion that just spoils the code and also leads to unexpected behavior

// should work, but don't
ip.getNetwork().getNetworkMask(ip.getPrefixLength()).toAddressString().getHostAddress();
// looks ugly, but works
ip.getNetwork().getNetworkMask(ip.getPrefixLength()).removePrefixLength();

Methods isValid() & isIPv4() failed to recognise invalid IP address

I am trying to validate IP address for further processing.

IPAddressString() & IPAddress() both are failing to recognise invalid ip string.

 IPAddressString ipstr = new IPAddressString("-");
 ipstr.isValid() //true
 ipstr.isIPv4()  //true

I think this.validate() is throwing error

Method threw 'java.lang.StackOverflowError' exception

.

`IPAddressSeqRange.join` joins upper addresses incorrectly

Hello,

First, thanks Sean for providing and maintaining this library. It has really been a lifesaver!

I think I found a bug in IPAddressSeqRange.join.

Imagine attempting to join two ranges, 10.120.20.10 - 10.120.20.14 and 10.120.20.14 - 10.120.20.20. If the second range's lower is less than or equal to the first range's upper, then it

  1. sets the second range to null, and
  2. returns the first range, except with the first range's upper set to the second range's upper.

This results in 10.120.20.10 - 10.120.20.20, which is correct.

However, using the same logic for 10.120.20.10 - 10.120.20.20 and 10.120.20.15 - 10.120.20.15 will result in 10.120.20.10 - 10.120.20.15, which is incorrect.
Instead of always taking the second range's upper, I feel like the correct thing to do is take whichever upper is greater between the first range and the second. Thoughts?

edit: I'm using version 5.1.0 for Java 11, but I believe it is still present on 5.2.1.

edit2: Also, sidenote but I believe this method mutates the array which is passed in. Reading the javadoc, I'm not sure if this was intentional so I thought I'd mention it.

Support for IPv6 as shown

Hello! Great library and thanks for your effort :)

I found it through the following SO answer:
https://stackoverflow.com/questions/577363/how-to-check-if-an-ip-address-is-from-a-particular-network-netmask-in-java/41482123#41482123

I was writing some unit tests against your answer and @omid's answer and found that your subnet test failed in the IPv6 example while his IpAddressMatcher passed.

Am I missing something?

Omid's Matcher:

import org.springframework.security.web.util.matcher.IpAddressMatcher;
...

private void checkIpMatch() {
    matches("192.168.2.1", "192.168.2.1"); // true
    matches("192.168.2.1", "192.168.2.0/32"); // false
    matches("192.168.2.5", "192.168.2.0/24"); // true
    matches("92.168.2.1", "fe80:0:0:0:0:0:c0a8:1/120"); // false
    matches("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/120"); // true
    matches("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/128"); // false
    matches("fe80:0:0:0:0:0:c0a8:11", "192.168.2.0/32"); // false
}

private boolean matches(String ip, String subnet) {
    IpAddressMatcher ipAddressMatcher = new IpAddressMatcher(subnet);
    return ipAddressMatcher.matches(ip);
}

My Unit Tests (in Kotlin):

enum class IPSUB (val ip: String, val subNet: String, val isOnSubNet: Boolean) {
        A("192.168.2.1", "192.168.2.1", true),
        B("192.168.2.1", "192.168.2.0/32", false),
        C("192.168.2.5", "192.168.2.0/24", true),
        D("92.168.2.1", "fe80:0:0:0:0:0:c0a8:1/120", false),
        E("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/120", true),
        F("fe80:0:0:0:0:0:c0a8:11", "fe80:0:0:0:0:0:c0a8:1/128", false),
        G("fe80:0:0:0:0:0:c0a8:11", "192.168.2.0/32", false),
        H("10.10.20.3", "10.10.20.0/30", true),
        I("10.10.20.5", "10.10.20.0/30", false),
        J("1::1", "1::/64", true),
        K("2::1", "1::/64", false),
        L("1::4:5", "1::3-4:5-6", true),
        M("2::", "1-2::/64", true),
        N("foo", "bar", false)
    }

@Test
    fun isIpOnSubnetsWithIpStringTest() {
        IPSUB.values().forEach {
            val ip = IPAddressString(it.ip)
            val sub = IPAddressString(it.subNet)
            println("IP:$ip Sub:$sub onSub:${sub.contains(ip)} expect:${it.isOnSubNet}")
            //Assertions.assertEquals(it.isOnSubNet, sub.contains(ip))
        }
    }

Facing problem with IPAddressString contains(IPAddressString other) method

Hello @seancfoley,
I am using contains method to check whether one IPAddressString contains other,

Examples,
192.168.1.0/24 contains 192.168.1.0/12.(true)
192.168.1.0/24 contains 192.168.2.0/24.(false)
192.168.1.1-10 contains 192.168.1.5-7.(true)
192.168.1.5-7 contains 192.168.1.1-10.(false)
192.168.. contains 192.168.1..(true)
192.168.1.
contains 192.168...(false)
192.168.1.0/24 contains 192.168.1.1-10.(true)
192.168.1.0/24 contains 192.168.2.1-10.(false)
192.168.1.* contains 192.168.1.0/24.(true)

All the above cases are working fine,but some of the below cases are failing,

  • Case-1
IIPAddressString ipAddressStringSubnetError1 = new IPAddressString( "10.162.155.1-51" );
        IPAddressString ipAddressStringSubnetError2 = new IPAddressString( "10.162.155.1-255" );
        System.out.println( String.format( "%s contains %s %s", ipAddressStringSubnetError2,
                ipAddressStringSubnetError1, ipAddressStringSubnetError2.contains( ipAddressStringSubnetError1 ) ) );

Output
10.162.155.1-255 contains 10.162.155.1-51 false

It should return true but it's returning false.But if ipAddressStringSubnetError1 range is 10.162.155.2-51 then it returns true.The problem only occurs when both ranges start with same address(10.162.155.1).

NOTE: Same problem is there for IPV6 also.

  • Case-2
IPAddressString ipAddressStringSubnetError3 =
                new IPAddressString( "2001:0db8:85a3:0000:0000:8a2e:0370:7334/120" );
        IPAddressString ipAddressStringSubnetError4 =
                new IPAddressString( "2001:0db8:85a3:0000:0000:8a2e:0370:7334/128" );
        System.out.println( String.format( "%s contains %s %s", ipAddressStringSubnetError3,
                ipAddressStringSubnetError4, ipAddressStringSubnetError3.contains( ipAddressStringSubnetError4 ) ) );

        System.out.println( String.format( "%s contains %s %s", ipAddressStringSubnetError4,
                ipAddressStringSubnetError3, ipAddressStringSubnetError4.contains( ipAddressStringSubnetError3 ) ) );

Output

2001:0db8:85a3:0000:0000:8a2e:0370:7334/120 contains 2001:0db8:85a3:0000:0000:8a2e:0370:7334/128 true

2001:0db8:85a3:0000:0000:8a2e:0370:7334/128 contains 2001:0db8:85a3:0000:0000:8a2e:0370:7334/120 true

Subnet Calculator

IP Address:	2001:0db8:85a3:0000:0000:8a2e:0370:7334/120
Full IP Address:	2001:0db8:85a3:0000:0000:8a2e:0370:7334
Total IP Addresses:	256
Network:	2001:0db8:85a3:0000:0000:8a2e:0370:7300
IP Range:	2001:0db8:85a3:0000:0000:8a2e:0370:7300 - 2001:0db8:85a3:0000:0000:8a2e:0370:73ff


IP Address:	2001:0db8:85a3:0000:0000:8a2e:0370:7334/128
Full IP Address:	2001:0db8:85a3:0000:0000:8a2e:0370:7334
Total IP Addresses:	1
Network:	2001:0db8:85a3:0000:0000:8a2e:0370:7334
IP Range:	2001:0db8:85a3:0000:0000:8a2e:0370:7334 - 2001:0db8:85a3:0000:0000:8a2e:0370:7334

In the case2 both are returning true, but 2001:0db8:85a3:0000:0000:8a2e:0370:7334/128 contains 2001:0db8:85a3:0000:0000:8a2e:0370:7334/120 should return false.

Note:
Same problem is there with IPV4 address also when address not end with zero.

-Case-3

IPAddressString ipAddressStringSubnetError5 = new IPAddressString( "192.13.1.0/25" );
        IPAddressString ipAddressStringSubnetError6 = new IPAddressString( "192.13.1.1-255" );
        System.out.println( String.format( "%s contains %s %s", ipAddressStringSubnetError5,
                ipAddressStringSubnetError6, ipAddressStringSubnetError5.contains( ipAddressStringSubnetError6 ) ) );
        System.out.println( String.format( "%s contains %s %s", ipAddressStringSubnetError6,
                ipAddressStringSubnetError5, ipAddressStringSubnetError6.contains( ipAddressStringSubnetError5 ) ) );

Output

192.13.1.0/25 contains 192.13.1.1-255 false
192.13.1.1-255 contains 192.13.1.0/25 false

In case3 i think 192.13.1.1-255 contains 192.13.1.0/25 should return true.

Thanks,
Vamsi.

Getting all subnets in a network

Hi, this is not an issue per say but rather a question. If i have a CIDR address for example "192.168.0.0/24", how would i get an iterator to all subnets in this network? Thanks for your help in advance.

IPv4 IPAddressString not containing another IPAddressString

According to http://jodies.de/ipcalc?host=10.0.0.1&mask1=24&mask2= , 10.0.0.1/24 starts at 10.0.0.1 and ends at 10.0.0.254. When trying to check with this lib if the upper bound of this subnet is contained within it, I'm getting false:

IPAddressString subnetStr = new IPAddressString("10.0.0.1/24");
IPAddressString ipStr = new IPAddressString("10.0.0.254");
subnetStr.contains(ipStr); // false

Oddly enough, both subnetStr.getAddress().getLower() and subnetStr.getAddress().getUpper() are both returning me 10.0.0.1.

I'm not an expert on networking and IP addresses, so pardon me if I'm missing something obvious.

Validation issue

Hi,

I've started to evaluate the IPAddress component and faced with few validation issues of IPAddressString.

For example: IPs like 127.0.1, 2001:____:a::123/64, 2001:0db8:85a3:-:0000:8a2e:0370:7334 are valid while they are not.
Is it an API bug or wrong validation configuration? For example, DEFAULT_VALIDATION_OPTIONS should be changed. If yes, what are right validation options that should be applied?

I see that:
127.0.1 transformed to 127.0.0.1
____ transformed to *
- transformed to *

How this transformation can be disabled?

Thanks,
Oleg.

Support for Binary IPv4

Hi, I am trying this code:

IPAddressString ipAddrStr = new IPAddressString("11000000.10101000.00000001.00000001");
if (ipAddrStr.isIPv4()) {
	try {
		IPAddress ipv4Addr = ipAddrStr.toAddress().toIPv4();
		if (ipv4Addr != null) {
			unescapedHost = ipv4Addr.toString();
		}
	} catch (AddressStringException e) {
		// Do something
	}
}

And ipAddrStr.isIPv4() returns false. Support for binary IPv4 could be added?

Thank you.

Cannot use library as Maven dependency when jitpack.io repo is added

For some reason jitpack.io repository has broken builds of some (not all versions of your library). These jars are almost empty and contain no classes at all.

I understand that jitpack.io builds packages "on demand" when any user first requests them but I don't understand why there are builds of your library there and why does not it have all the versions. For example, it already has 5.3.3 version but does not have 5.3.0.

Also I don't know why does it even publishes anything (Brief look at this page suggests that by default it tries to run build tools from the root of the repo and mvn install -DskipTests definitely fails if you run it from the root of the repo).

Also I don't know how to solve it. Maybe it's possible to make your repo jitpack-compatible by providing jitpack.yml (probably we do not consider changing the artifact name).

toInetAddress() question

I'm trying this

import inet.ipaddr.*;

public class MyClass {
    public static void main(String args[]) {
        try {
            IPAddress addr = new IPAddressString("::/0").toAddress();
            System.out.println(addr.getNetworkPrefixLength());
            System.out.println(addr.toInetAddress().getHostAddress());
        } catch(Exception e) {
            System.out.println(e);
        }
    }
}

which gives

0
ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff

But according to documentation toInetAddress() should give the lowest of the range which I suppose should be 0:0:0:0:0:0:0:0 no?

I have no idea about CIDR and IP in general so If I'm mistaken apologies in advance.

Duplicate property key

IPAddressResources.properties
ipaddress.error.splitMismatch=splitting digits in segments results in an invalid string (eg 12-22 becomes 1-2.2-2 which is 12 and 22 and nothing in between)
ipaddress.error.splitMismatch=split segments cannot be range segments

Failing IPv4 membership check

Hi,

I'm trying to integrate IPAddress to my project but some unit tests fail unexpectedly. These unit tests are checking membership of an IP address in a CIDR. Let me share one;

IPAddressString cidr = new IPAddressString("217.152.89.223/27");
IPAddressString ip = new IPAddressString("217.152.89.198");
assertThat(cidr.contains(ip)).isTrue();

I expect this test to be true for any IP within [217.152.89.192 - 217.152.89.223] inclusive range and one of them is used here.

I use com.github.seancfoley:ipaddress:5.3.1.

Appreciate any help on resolving this. Thanks in advance.

Merge Subnet Ranges

What i want to achieve with this library is something mentioned here?

https://github.com/flowchartsman/cidr-convert

Is is possible? I have seen examples on SO. but nothing similar to this c equivalent.
Could you please take a look and potentially provide some examples to give an idea on how to implement?

Cheers

Iterate the IPv6 address range

I recently parse IPv6 address section to get all the IPv6 addresses in the section. But I came across a problem. Here is the code:
`

        IPAddress testAddress = new IPAddressString("2401:b180:1:4:f000::/120").getAddress();
        for (IPAddress ipv6AddressIter : testAddress.getIterable()) {
            System.out.println(ipv6AddressIter.toCompressedString());
        }`

I get addresses from 2401:b180:1:4:f000::/120 to 2401:b180:1:4:f0ff::/120, But I want to get the exact address without prefix, so I change the code to the following:
`

        IPAddress testAddress = new IPAddressString("2401:b180:1:4:f000::/120").getAddress();
        for (IPAddress ipv6AddressIter : testAddress.getIterable()) {
            System.out.println(ipv6AddressIter.removePrefixLength().toCompressedString());
        }`

But out of expectation, I get 256 same addresses which are all 2401:b180:1:4:f000::

So I change to IPAddress from 4.2.0 to 3.0.0, now I can get all the address from 2401:b180:1:4:f000:: to 2401:b180:1:4:f000::ff.

Does anyone know what is the problem?

Hex IPv4 address NOT understood as IPv4

I have hex 000000000000000000000000C0A80000 IPV4 address . Its decimal form is 192.168.0.0. I do want to check whether hex ip is of type IPV4 or IPV6.

isIPv4() is returning FALSE for above IPV4 address and saying it as IPV6.

new IPAddressString("000000000000000000000000C0A80000").getAddress().isIPv6() //true
new IPAddressString("000000000000000000000000C0A80000").getAddress().isIPv4() //false

I think leading zeros creating issue. Because of leading zeros it is exceeding length of standard IPv4 length hence it is giving it as IPv6.

Checking whether a wildcard contains an IP address not working

* <li>wildcards '*' and ranges '-' (for example 1.*.2-3.4), useful for working with subnets</li>

According to the above line, one should be able to test whether an IP address falls withing a wildcard range. I've found that asterisks work but ranges do not work. As an example here is code that can be tested in groovyConsole:

@Grab(group='com.github.seancfoley', module='ipaddress', version='5.2.1')

import inet.ipaddr.IPAddressString

IPAddressString myIp = new IPAddressString('108.31.1.1') 
IPAddressString ipRange = new IPAddressString('108.30-31.*.*') 

println ipRange.contains(myIp)

If you change myIp to 108.30.1.1 it returns true. Expanding the range to 30-39 doesn't have any affect.

It seems to not working correctly.

The code below doesn't work correctly. It is suppose to return all true, but only the first line gives true others give false.

`package com.mycompany.ipaddresstests;

import inet.ipaddr.*;

public class MainTests {

public static void main(String[] args) {
IPAddress address = new IPAddressString("10.132.0.1/16").getAddress();

System.out.println(address.contains(new IPAddressString("10.132.0.1").getAddress()));
System.out.println(address.contains(new IPAddressString("10.132.1.1").getAddress()));
System.out.println(address.contains(new IPAddressString("10.132.2.1").getAddress()));
System.out.println(address.contains(new IPAddressString("10.132.3.1").getAddress()));

}
}
`

Missing requirement "inet.ipaddr"

Hi, my maven project builds fine after importing your libraries. But when running, the bundle is not able to launch due to errors. Any tips here?
My imports:

import inet.ipaddr.IPAddress;
import inet.ipaddr.IPAddressString;

Example of how i used it (if i remove this line, everything works fine):
public IPAddress global_net = new IPAddressString("192.168.0.1/24").getAddress();

Already added below dependency to pom.xml.

<dependency>
        <groupId>com.github.seancfoley</groupId>
        <artifactId>ipaddress</artifactId>
        <version>5.0.0</version>
</dependency>

Error:

Could not start bundle mvn:com.intel.rsd.onos/main/1.0-SNAPSHOT in feature(s) main-1.0-SNAPSHOT: Unresolved constraint in bundle com.intel.rsd.onos.main [221]: Unable to resolve 221.0: missing requirement [221.0] osgi.wiring.package; (osgi.wiring.package=inet.ipaddr)
at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeature(FeaturesServiceImpl.java:403)
at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeature(FeaturesServiceImpl.java:371)
at org.apache.karaf.features.internal.FeaturesServiceImpl.installFeature(FeaturesServiceImpl.java:349)
at Proxy31184b0b_27d3_4cd4_87ac_ea2d42dceecb.installFeature(Unknown Source)
at org.onosproject.app.impl.ApplicationManager.installAppFeatures(ApplicationManager.java:283)
at org.onosproject.app.impl.ApplicationManager.access$200(ApplicationManager.java:66)
at org.onosproject.app.impl.ApplicationManager$InternalStoreDelegate.notify(ApplicationManager.java:210)
at org.onosproject.app.impl.ApplicationManager$InternalStoreDelegate.notify(ApplicationManager.java:202)
at org.onosproject.store.AbstractStore.notifyDelegate(AbstractStore.java:58)[142:org.onosproject.onos-api:1.15.0.SNAPSHOT]
at org.onosproject.store.app.DistributedApplicationStore.access$800(DistributedApplicationStore.java:99)[146:org.onosproject.onos-core-dist:1.15.0.SNAPSHOT]
at org.onosproject.store.app.DistributedApplicationStore$AppActivator.accept(DistributedApplicationStore.java:530)[146:org.onosproject.onos-core-dist:1.15.0.SNAPSHOT]
at org.onosproject.store.app.DistributedApplicationStore$AppActivator.accept(DistributedApplicationStore.java:523)[146:org.onosproject.onos-core-dist:1.15.0.SNAPSHOT]
at org.onosproject.store.atomix.primitives.impl.AtomixDistributedTopic.lambda$null$0(AtomixDistributedTopic.java:63)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)[:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)[:1.8.0_191]
at java.lang.Thread.run(Thread.java:748)[:1.8.0_191] >

Android compile error

Although I can work with ipaddress outside of an android project, when I'm trying in one I get this error

ipaddress-5.0.1.jar: D8: Illegal class file: Class module-info is missing a super type.

Any ideas?

How can i get the ip class? from a IPAddress

code:

IPAddress address = new IPAddressString(ip).getAddress();
IPAddress mask = address.getNetwork().getNetworkMask(16, false);
IPAddressSection network;
network = address.getNetworkSection(16, true);
BigInteger range = address.getSequentialBlockCount();

IP network mask

Suppose, we have an adress string and ones need to get IPv4 netmask address in octet format.

IPAddress ipv4Address = new IPAddressString("1.2.3.4/24").toAddress();
System.out.println(ipv4Address.getNetwork().getNetworkMask(ipv4Address.getNetworkPrefixLength()));

This code does its work, but it literally requires to specify the network prefix twice. First in the address string and then as arg in getNetworkMask(). Would it be possible to add getNetworkMask() method to IPAddress or inherit prefix length from IPAddress in getNetwork() ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.