2
0

ipcalc.sh 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/bin/sh
  2. awk -f - $* <<EOF
  3. function bitcount(c) {
  4. c=and(rshift(c, 1),0x55555555)+and(c,0x55555555)
  5. c=and(rshift(c, 2),0x33333333)+and(c,0x33333333)
  6. c=and(rshift(c, 4),0x0f0f0f0f)+and(c,0x0f0f0f0f)
  7. c=and(rshift(c, 8),0x00ff00ff)+and(c,0x00ff00ff)
  8. c=and(rshift(c,16),0x0000ffff)+and(c,0x0000ffff)
  9. return c
  10. }
  11. function ip2int(ip) {
  12. for (ret=0,n=split(ip,a,"\."),x=1;x<=n;x++) ret=or(lshift(ret,8),a[x])
  13. return ret
  14. }
  15. function int2ip(ip,ret,x) {
  16. ret=and(ip,255)
  17. ip=rshift(ip,8)
  18. for(;x<3;ret=and(ip,255)"."ret,ip=rshift(ip,8),x++);
  19. return ret
  20. }
  21. function compl32(v) {
  22. ret=xor(v, 0xffffffff)
  23. return ret
  24. }
  25. BEGIN {
  26. slpos=index(ARGV[1],"/")
  27. if (slpos == 0) {
  28. ipaddr=ip2int(ARGV[1])
  29. dotpos=index(ARGV[2],".")
  30. if (dotpos == 0)
  31. netmask=compl32(2**(32-int(ARGV[2]))-1)
  32. else
  33. netmask=ip2int(ARGV[2])
  34. } else {
  35. ipaddr=ip2int(substr(ARGV[1],0,slpos-1))
  36. netmask=compl32(2**(32-int(substr(ARGV[1],slpos+1)))-1)
  37. ARGV[4]=ARGV[3]
  38. ARGV[3]=ARGV[2]
  39. }
  40. network=and(ipaddr,netmask)
  41. broadcast=or(network,compl32(netmask))
  42. start=or(network,and(ip2int(ARGV[3]),compl32(netmask)))
  43. limit=network+1
  44. if (start<limit) start=limit
  45. end=start+ARGV[4]
  46. limit=or(network,compl32(netmask))-1
  47. if (end>limit) end=limit
  48. print "IP="int2ip(ipaddr)
  49. print "NETMASK="int2ip(netmask)
  50. print "BROADCAST="int2ip(broadcast)
  51. print "NETWORK="int2ip(network)
  52. print "PREFIX="32-bitcount(compl32(netmask))
  53. # range calculations:
  54. # ipcalc <ip> <netmask> <start> <num>
  55. if (ARGC > 3) {
  56. print "START="int2ip(start)
  57. print "END="int2ip(end)
  58. }
  59. }
  60. EOF