开发者

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.开发者_JAVA百科1.1.2

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


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!


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜