user683861
user683861

Reputation: 1

to which subnet IP address belongs?

I have to write a script in bash , perl or python. I got file with three columns (for manually manage connect-proxy)

SUBNET/IP         socks_port        socks_ip 
1.2.3.*              1080             9.8.7.6
1.1.*                1080             6.8.7.6

I want to know to which subnet belongs IP address, for example:

$ my_script  1.1.1.2

this IP belongs to 1.1.* subnet so I want back second line.

Upvotes: 0

Views: 1714

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125828

If the file is in the format given (i.e. using *), it'll be fairly easy to use bash pattern matching to compare this to the ip address. However, as @Mark Drago pointed out, this format anything except octet-boundary subnets, so if you need to support arbitrary subnet boundaries, you need a better format.

Assuming you are using the "1.2.*" format, this should work:

#!/bin/bash
ip="$1"
found_match=false
while read subnet socks_port socks_ip; do
    if [[ "$ip" == $subnet ]]; then  # this'll do glob-style pattern matching against $subnet
        echo "subnet=$subnet, socks_port=$socks_port, socks_ip=$socks_port"
        found_match=true
        break  # assuming you don't want to check for multiple matches
    fi
done </path/to/subnet/file

if ! $found_match; then
    echo "No match found in subnet file"
fi

Upvotes: 0

salezica
salezica

Reputation: 76949

BASH: quick and dirty, use cut, then grep over the file.

PYTHON: use ip.rsplit() and then line.split()[].startswith() iterating through the file.

PERL: no idea.

Cheers!

Upvotes: 1

Related Questions