ipcalc.sh 1.8 KB

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