我有一个包含IP的文件,我想将它与使用本地数据库(而不是API)的Coordinates进行比较.
16777216 16777471 AU Australia Queensland Brisbane -27.467940 153.028090
16777472 16778239 CN China Fujian Fuzhou 26.061390 119.306110
16778240 16779263 AU Australia Victoria Melbourne -37.814000 144.963320
16779264 16781311 CN China Guangdong Guangzhou 23.116670 113.250000
IP地址文件:
131.72.136.65
131.72.138.204
131.72.138.45
131.72.139.112
131.72.139.163
所以首先我将IP修改为十进制,以便我可以进行比较.
IP2Dec
#!/bin/bash
# while read line; do echo "$line"; done < iplist.txt
ip2dec () {
local a b c d ip=$@
IFS=. read -r a b c d <<< "$ip"
printf '%d\n' "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"
}
ip2dec "$@"
我比较了IP和DB文件,并使用下面的脚本打印了IP,Lat,Long.
awk 'NR == FNR { x[$1] = $1+0; next; } { for (i in x) { if (x[i] > $1+0 && x[i] < $2+0) { print x[i], $NF-1, $NF;} } }' ip.txt db.txt
所以现在输出是,
387306133 -78.4875 -77.487490
399341146 -105.985 -104.984700
399478903 -105.985 -104.984700
401285510 -123.395 -122.395200
401289024 -123.395 -122.395200
520966134 102.85 103.850070
现在我想将Decimal转换回IP地址,
#!/bin/bash
dec2ip () {
local ip dec=$@
for e in {3..0}
do
((octet = dec / (256 ** e) ))
((dec -= octet * 256 ** e))
ip+=$delim$octet
delim=.
done
printf '%s\n' "$ip"
}
dec2ip "$@"
但这会转换整个文件,我只想转换第一列并保留Lad和Lon.
我试图将所有这些零碎的东西组合起来做一份工作.
此外,这是一种有效的方式吗?最终,我希望在Google地图上绘制这些IP.
解决方法:
除了需要的IP2Dec和dec2ip脚本
只在部分文件上执行,它应该工作.
这里是一个仅应用函数的dec2ip示例
该行的第一个条目.
#!/bin/bash
dec2ip () {
local ip dec=$@
delim=""
for e in {3..0}
do
((octet = dec / (256 ** e) ))
((dec -= octet * 256 ** e))
ip+="$delim$octet"
delim=.
done
printf '%s' "$ip"
}
while read IP lon lat ; do
dec2ip $IP
printf " %s %s\n" "$lon" "$lat"
done
更好的方法是用更高级别的语言简短地编写所有内容.
以下python 2.7脚本应该执行您需要的任务(它没有优化
速度):
#!/usr/bin/python
import socket,struct
db=[]
for l in open("db.txt"):
fields=l.split();
db.append((int(fields[0]),int(fields[1]),fields[-2],fields[-1]))
for l in open("ip.txt"):
ip=struct.unpack('!I',socket.inet_aton(l))[0]
for e in db:
if e[0]<=ip<=e[1]:
print l.strip(),e[2],e[3]
break
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。