2012-03-19 8 views
7

El código siguiente para convierte una dirección IP a un int de una manera muy rápida:¿Cómo uso BitShifting para convertir una dirección IP basada en int a una cadena?

static int ipToInt(int first, int second, int third, int fourth) 
    { 
     return (first << 24) | (second << 16) | (third << 8) | (fourth); 
    } 

source

Pregunta

¿Cómo se utiliza el desplazamiento de bits para convertir el valor de nuevo a una ¿Dirección IP?

+0

posible duplicado de [Cómo convertir un int a un pequeño conjunto de bytes endian?] (Http://stackoverflow.com/questions/2350099/how-to-convert-an-int-to-a- little-endian-byte-array) –

+0

@OliCharlesworth He intentado 'nueva IPAddress (BitConverter.GetBytes (i))' pero eso requiere un formato endian diferente de lo que ofrece mi enfoque actual – LamonteCristo

+1

Una respuesta de trabajo completa está disponible aquí http: //stackoverflow.com/a/9775647/328397 – LamonteCristo

Respuesta

4

Pruebe lo siguiente

static out intToIp(int ip, out int first, out int second, out int third, out int fourth) { 
    first = (ip >> 24) & 0xFF; 
    second = (ip >> 16) & 0xFF; 
    third = (ip >> 8) & 0xFF; 
    fourth = ip & 0xFF; 
} 

o para evitar una excesiva número de parámetros de salida, utilice un struct

struct IP { 
    int first; 
    int second; 
    int third; 
    int fourth; 
} 

static IP intToIP(int ip) { 
    IP local = new IP(); 
    local.first = (ip >> 24) & 0xFF; 
    local.second = (ip >> 16) & 0xFF; 
    local.third = (ip >> 8) & 0xFF; 
    local.fourth = ip & 0xFF; 
    return local; 
} 

Pregunta general : ¿Por qué está usando int aquí en lugar de byte?

+0

Tengo la intención de incrementar la dirección IP en rangos de subred de clase C, pero no quiero dar cuenta para 255 en cada octeto en el código. – LamonteCristo

3

Asumiendo que su código es correcto, basta con invertir los bits turnos y Y el resultado con 0xFF a caer trozos espurias:

first = (ip >> 24) & 0xff; 
second = (ip >> 16) & 0xff; 
third = (ip >> 8) & 0xff; 
fourth = ip & 0xff; 
+0

Gracias, el 0xff es parte de mi problema. Necesito aprender por qué ese es un personaje especial. Apuesto a que significa EOF o nulo. – LamonteCristo

+0

@ makerofthings7 '0xFF' representa un solo byte donde todos los bits se establecen en' 1. El '& 0xFF' asegura que todo lo que no sea el byte menos significativo se establezca en' 0' – JaredPar

+0

Ahh Veo, eso tiene sentido – LamonteCristo

1

Para completar (y como una forma de devolver a la comunidad) esta es la forma de convertir un rango de IP en una lista.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Net; 

namespace NormalizeIPRanges 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      if (!BitConverter.IsLittleEndian) 
       // http://stackoverflow.com/a/461766/328397 
       throw new NotSupportedException ("This code requires a little endian CPU"); 

      // IPv4 
      string input = "64.233.187.98 - 64.233.188.2"; 
      var ipRange = input.Replace(" ", "").Split("-".ToCharArray()); 

      if (ipRange.Length == 2) 
      { 
       var startBytes =IPAddress.Parse(ipRange[0]).GetAddressBytes(); 
       var stopBytes = IPAddress.Parse(ipRange[1]).GetAddressBytes(); 

       if (startBytes.Length != 4 || stopBytes.Length != 4) 
       { 
        // Note this implementation doesn't imitate all nuances used within MSFT IP Parsing 
        // ref: http://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx 

        throw new ArgumentException("IP Address must be an IPv4 address"); 
       } 

       // IP addresses were designed to do bit shifting: http://stackoverflow.com/a/464464/328397 
       int startAddress = ipToInt(startBytes[0], startBytes[1], startBytes[2], startBytes[3]); 
       var t =intToIP(startAddress); 

       int stopAddress = ipToInt(stopBytes[0], stopBytes[1], stopBytes[2], stopBytes[3]); 
       var tr = intToIP(stopAddress); 


       for (int i = startAddress; i <= stopAddress; i++) 
       { 
        Console.WriteLine(intToIP(i)); 
       } 
      } 
     } 

     static int ipToInt(int first, int second, int third, int fourth) 
     { 
      return (first << 24) | (second << 16) | (third << 8) | (fourth); 
     } 
     static string intToIP(int ip) 
     { 
      var a = ip >> 24 & 0xFF; 
      var b = ip >> 16 & 0xFF; 
      var c = ip >> 8 & 0xFF; 
      var d = ip & 0xFF; 

      return String.Format("{0}.{1}.{2}.{3}",a,b,c,d); 
     } 

    } 
} 
Cuestiones relacionadas