• Post Reply Bookmark Topic Watch Topic
  • New Topic

function for IP address to integer conversion  RSS feed

 
MaheshS Kumbhar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I need to know, is there any in-built function available that can convert the IP address to an integer value. I can do it by writing own function, but I want to know if is there any in-built function available?

Thanks in advacne
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use InetAddress.hashCode()
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That would ofcourse give you the hash code of the InetAddress object. Are you sure that that is what you need, or do you need some specific requirement of what the integer should contain?
 
MaheshS Kumbhar
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, hashcod will give the hashcode representation of InetAddress object, but this is not what I want. I want the integer reprsentation of the IP address string. For example, suppose IP address is "192.168.1.0", then I want the integer value of this IP address. I can get integer value from this manually by doing [192*(256^3)+168*(256^2)+1*256+0]

Is there any in-built function that can do this for me?

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think there is a built-in method to do this for you, so you'd have to implement this yourself.

Ofcourse this will only work for 4-digit IPv4 addresses. Please note that the IPv4 addresses are getting exhausted, and more and more networks will switch to IPv6. Your program will probably not work anymore on a network that requires IPv6 addresses.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The best I can come up with is

 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would set an explicit endian to make sure that you don't use big endian instead of little endian.
Or just do it manually:
The << 8 part is equivalent to multiplying by 256, the b & 0xFF turns possible negative values into positive values (e.g. -1 becomes 255), and the | is equivalent to adding (but only because the << 8 ensures the last 8 bits are all 0 and the b & 0xFF part will have only the last 8 bits set).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!