[英]Bash script to convert decimal IP to binary
I need to write a script to enter 2 IP addresses and then change them to binary. 我需要编写一个脚本来输入2个IP地址,然后将其更改为二进制。 I tried this script but it works just with numbers.
我尝试了此脚本,但它仅适用于数字。 I can't write the IP thus:
192.168.1.1
, but when I write it as 100
it's working fine. 我不能这样写IP:
192.168.1.1
,但是当我写为100
它可以正常工作。
#!/bin/bash
echo "Ebter the first ip"
read ip1
echo "Enter the second ip"
read ip2
a=`echo "obase=2;$ip1" | bc`
b=`echo "obase=2;$ip2" | bc`
echo $a
echo $b
What is wrong in my script? 我的脚本有什么问题?
what you can do: 你可以做什么:
#!/bin/bash
function convip()
{
CONV=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
ip=""
for byte in `echo ${1} | tr "." " "`; do
ip="${ip}.${CONV[${byte}]}"
done
echo ${ip:1}
}
echo "Enter the first ip"
read ip1
echo "Enter the second ip"
read ip2
a=`convip "${ip1}"`
b=`convip "${ip2}"`
echo "${a}"
echo "${b}"
Result: 结果:
Enter the first ip
1.1.1.1
Enter the second ip
2.2.2.2
00000001.00000001.00000001.00000001
00000010.00000010.00000010.00000010
EDIT: updated to keep dots 编辑:更新以保留点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.