Pregunta

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
¿Fue útil?

Solución

string s = "174.36.207.186";

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

Otros consejos

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);

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top