3

That does this calculation below

address = '174.36.207.186'

( o1, o2, o3, o4 ) = address.split('.')

integer_ip =   ( 16777216 * o1 )
             + (    65536 * o2 )
             + (      256 * o3 )
             +              o4
6
  • possible duplicate of How to convert an IPv4 address into a integer in C#? Dec 21, 2012 at 22:12
  • Look here
    – Jordão
    Dec 21, 2012 at 22:13
  • i checked both place and did not find working solution. first of all it has to be int 64 not 32 Dec 21, 2012 at 22:13
  • Int32 would not support addresses larger than 127.255.255.255; however, UInt32 would support the full IPv4 range. Int64 would be overkill.
    – Douglas
    Dec 21, 2012 at 22:21
  • I think that the solution from @Douglas is far better than the duplicate signaled. Let this question and its answer open please
    – Steve
    Dec 21, 2012 at 22:41

3 Answers 3

7
string s = "174.36.207.186";

uint i = s.Split('.')
          .Select(uint.Parse)
          .Aggregate((a, b) => a * 256 + b);
0
2

You can parse the numbers into a byte array, then use BitConverter.ToInt32 to put them together into an int:

byte[] parts = address.Split('.').Select(Byte.Parse).ToArray();
if (BitConverter.IsLittleEndian) {
  Array.Reverse(parts);
}
int ip = BitConverter.ToInt32(parts, 0);
3
  • 1
    Int32 only supports addresses up to 127.255.255.255.
    – Douglas
    Dec 21, 2012 at 22:22
  • @Douglas: Not at all. Addresses higher than that are represented as negative int values. You can cast the int it to uint if you like that better.
    – Guffa
    Dec 21, 2012 at 23:39
  • Fair point. I should have said that the intent is less clear with negative numbers. For example, any assumed ordering would be broken; 127.0.0.0 < 128.0.0.0 would evaluate as false using Int32 representations.
    – Douglas
    Dec 22, 2012 at 10:10
2

You can parse the string to an IPAddress instance and then access the Address Property:

long result = IPAddress.Parse("174.36.207.186").Address;

Note that this will yield a compiler warning (obsolete property), because it doesn't work with IPv6.

3
  • not returnign same value for example ip : 1.0.145.221 returns : 3717267457 while it should return : 16814557 Dec 21, 2012 at 22:24
  • Maybe you need NetworkToHostOrder?
    – dtb
    Dec 21, 2012 at 22:27
  • how to use it ? i tried several combinations but does not accept ip as parameter Dec 21, 2012 at 22:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.