gyorgyabraham
gyorgyabraham

Reputation: 2608

Match public IP addresses with user-supplied netmasks

Recently I was given a task at my company where I have to create a function like this:

boolean addrMatch(String IP, String netMask);

This has nothing to do with routing. We have a network service that will use this function. The IP parameter varies upon all requests, the netMask parameter is user-supplied. The function must tell that an actual IP address matches with the supplied netmask or not. This is something like the user tells our system to only serve requests on the public internet to a specific subset of IP addresses, not all of them. My networking related knowledge is far from complete, so I did a deep search on the topic, but I didn't get very far. What I know (or been told): all the two parameteres are valid IP addresses or netmasks in xxx.xxx.xxx.xxx notation. I have to do a bitwise AND on them (obviously after converting them into BitSet or at least byte[] array). But I guess this is not the complete algorithm. So my question: what is the correct algorithm for matching an IP address with a netmask?

ps.: I'm working in Java, but I need the generic method.

Upvotes: 1

Views: 491

Answers (1)

user207421
user207421

Reputation: 311028

A netmask is just a bitmask. Basically if address & netmask != 0 the address is in the subnet represented by the netmask. The implementation details you have to cope with are bytes instead of bits, and varying numbers of bytes depending on whether you have IPv4 or IPv6. But it's basically trivial.

Upvotes: 0

Related Questions