Les Snippets

Connexion

Convertir une IP en long et un long en IP ( IP2Long, Long2IP )

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 02/04/2006 13:40:00 et initié par Nix [Liste]
Date de mise à jour : 04/11/2007 13:16:41
Vue : 34260
Catégorie(s) : Réseau & Internet, Web
Langages dispo pour ce code :
- ASP.NET 2.x, VB 2005
- C# 1.x
- C# 2.x
- PHP 4, PHP 5
- VB6, VBA
- C, C++, C++ .NET 1.x, C++ .NET 2.x
- mySQL
- SQL 2005
- Python



Langage : VB 2005 , ASP.NET 2.x
Date ajout : 02/04/2006
Posté par Nix [Liste]
DateMAJ : 02/04/2006

Public Shared Function IPToLong(ByVal ipAddress As String) As Long

    Try
        Dim ip As System.Net.IPAddress = Net.IPAddress.Parse(ipAddress) 
        Return (CLng(ip.GetAddressBytes(0)) << 24) Or (CInt(ip.GetAddressBytes(1)) << 16) Or (CInt(ip.GetAddressBytes(2)) << 8) Or ip.GetAddressBytes(3)
    Catch ex As Exception 
        Return 0 
    End Try


End Function



Public Shared Function LongToIP(ByVal ipAddress As Long) As String

    Try
        Dim tmpIP As New Net.IPAddress(ipAddress)
        Dim bytes() As Byte = tmpIP.GetAddressBytes() 
        Array.Reverse(bytes)
        Dim addr As Long = CLng(BitConverter.ToUInt32(bytes, 0))
        Return New Net.IPAddress(addr).ToString() 
    Catch ex As Exception

        Return ex.Message 
    End Try

End Function

'Exemple d'utilisation

Dim IPFromLong As Long = IPToLong("127.0.0.1") ' Retournera 2130706433

Dim IPFromString As String = LongToIP(2130706433) ' Retournera "127.0.0.1"

Langage : C# 1.x
Date ajout : 03/04/2006
Posté par MorpionMx [Liste]
DateMAJ : 01/05/2006
public static long IPToLong(string ipAddress) 
{
    try

    {
       System.Net.IPAddress ip = System.Net.IPAddress.Parse(ipAddress); 
       return (((long)ip.GetAddressBytes()[0] << 24) | ((int)ip.GetAddressBytes()[1] << 16) | ((int)ip.GetAddressBytes()[2] << 8) | ip.GetAddressBytes()[3]); 
    }
    catch (Exception) 
    {
        return 0; 
    }
}

public static string LongToIP(long ipAddress) 
{
    try

    {
        System.Net.IPAddress tmpIp = System.Net.IPAddress.Parse(ipAddress.ToString()); 
        Byte[] bytes = tmpIp.GetAddressBytes();   
        long addr = (long)BitConverter.ToInt32(bytes, 0);
        return new System.Net.IPAddress(addr).ToString(); 
    }
    catch (Exception e) { return e.Message; } 
}

// Exemples d'utilisations

// long longFromIP = IpToLong("127.0.0.1"); // retournera 2130706433

// string ipFromLong = LongToIo(2130706433); // retournera 127.0.0.1



Langage : C# 2.x
Date ajout : 03/04/2006
Posté par MorpionMx [Liste]
DateMAJ : 01/05/2006
public static long IPToLong(string ipAddress) 
{
    System.Net.IPAddress ip; 
    if (System.Net.IPAddress.TryParse(ipAddress, out ip))
    return (((long)ip.GetAddressBytes()[0] << 24) | ((int)ip.GetAddressBytes()[1] << 16) | ((int)ip.GetAddressBytes()[2] << 8) | ip.GetAddressBytes()[3]);    else return 0; 
}


public static string LongToIP(long ipAddress) 
{

    System.Net.IPAddress tmpIp;
    if (System.Net.IPAddress.TryParse(ipAddress.ToString(), out tmpIp)) 
    {

        try

        {
            Byte[] bytes = tmpIp.GetAddressBytes(); 
            long addr = (long)BitConverter.ToInt32(bytes, 0);
            return new System.Net.IPAddress(addr).ToString(); 
        }
        catch (Exception e) { return e.Message; } 
    }
    else return String.Empty; 
}


// Exemples d'utilisations

// long longFromIP = IpToLong("127.0.0.1"); // retournera 2130706433

// string ipFromLong = LongToIo(2130706433); // retournera 127.0.0.1


Remarque :
Utilisation des méthodes TryParse() (plutot que de Parse() en .Net 1.x), qui ne lève pas d'exception
Langage : PHP 4 , PHP 5
Date ajout : 03/04/2006
Posté par malalam [Liste]

<?php
$sString = '127.0.0.1';
$long = ip2long ($sString);
$ip = long2ip ($long);

echo $long, '<br />';
echo $ip;
?>

Langage : VB6 , VBA
Date ajout : 03/04/2006
Posté par EBArtSoft [Liste]
DateMAJ : 03/04/2006

Private Declare Function inet_addr Lib "wsock32.dll" (ByVal addr As String) As Long
Private Declare Function inet_ntoa Lib "wsock32.dll" (ByVal addr As Long) As Long
Private Declare Function lstrcpy Lib "kernel32" Alias "lstrcpyA" (ByVal lpString1 As String, ByVal lpString2 As Long) As Long

     
    'Transforme une IP en long
    Dim i As Long
    i = inet_addr("127.0.0.1")
    Debug.Print i
    
    'Transforme un long en IP
    Dim p As String * 32
    lstrcpy p, inet_ntoa(i)
    Debug.Print p


Remarque :
VB.NET egalement
Langage : C , C++ , C++ .NET 1.x , C++ .NET 2.x
Date ajout : 04/06/2006
Posté par katsankat [Liste]
// Portabilité: Win32/Linux
 #include <stdio.h> 
  
 #ifndef WIN32 
    #include <arpa/inet.h> 
 #else 
    #include <winsock2.h> 
 #endif 
  
 char* long2ip(unsigned int v) 
 { 
   struct in_addr x; 
   x.s_addr = htonl(v); // passe dans l' ordre reseau 
   return inet_ntoa(x); // et convertit 
 } 
  
 unsigned int ip2long(char *s) 
 { 
   struct sockaddr_in n; 
   #ifndef WIN32 
    inet_aton(s,&n.sin_addr); 
    return ntohl(n.sin_addr.s_addr); 
  #else 
    return ntohl(inet_addr(s)); 
   #endif 
 } 
  
  
 int main(int argc, char *argv[]) 
 { 
  // ip2long 
  char* str="127.0.0.1"; 
  unsigned int f = ip2long(str); 
  printf( "ip2long(%s) => %u\n\n", str, f ); 
  
  // long2ip 
  printf( "long2ip(2130706433) => %s\n", long2ip(2130706433) ); 
  
  return 0; 
 } 
 

Langage : mySQL
Date ajout : 09/06/2007
Posté par coucou747 [Liste]
CREATE FUNCTION long2ip (ip INT UNSIGNED)
RETURNS TEXT DETERMINISTIC
RETURN CONCAT(FLOOR(ip/(256*256*256)), '.', (FLOOR(ip/(256*256)))%256, '.', (FLOOR(ip/256))%256, '.', ip%256);
CREATE FUNCTION ip2long (ip TEXT)
RETURNS INT UNSIGNED DETERMINISTIC
BEGIN
    DECLARE i INT DEFAULT 1;
    DECLARE r INT UNSIGNED DEFAULT 0;
    DECLARE p INT UNSIGNED DEFAULT 0;
    WHILE i <= LENGTH(ip) DO
        IF SUBSTRING(ip, i, 1) = '.' THEN
            SET r = r * 256+p;
            SET p = 0;
        ELSE
            SET p = p*10 + ASCII(SUBSTRING(ip, i, 1)) - ASCII('0');
        END IF;
        SET i = i + 1;
    END WHILE;
    RETURN r*256+p;
END

Langage : SQL 2005
Date ajout : 04/11/2007
Posté par skweeky [Liste]
DateMAJ : 04/11/2007

CREATE FUNCTION dbo.ConvertIntToIp ( @AddrInt int )

RETURNS varchar(15)

BEGIN

RETURN CAST(CAST(CAST(( @AddrInt & 0xFF000000 ) / 0x01000000 AS binary(1)) as tinyint) as varchar(3))

+ '.'

+ CAST(CAST(CAST(( @AddrInt & 0xFF0000 ) / 0x010000 AS binary(1)) as tinyint) as varchar(3))

+ '.'

+ CAST(CAST(CAST(( @AddrInt & 0xFF00 ) / 0x0100 AS binary(1)) as tinyint) as varchar(3))

+ '.'

+ CAST(CAST(CAST(( @AddrInt & 0xFF ) AS binary(1)) as tinyint) as varchar(3))

END

GO

CREATE FUNCTION dbo.ConvertIpToInt ( @AddrIp varchar(15) )
RETURNS int 
BEGIN
DECLARE @first smallint 
DECLARE @second smallint

DECLARE @third smallint

DECLARE @fourth smallint

DECLARE @result int

DECLARE @test varchar(4)

DECLARE @cur_loc tinyint

DECLARE @last_loc tinyint

-- Premier Bloc

SET @cur_loc = CHARINDEX('.', @AddrIp)

SET @test = LEFT(LEFT(@AddrIp, @cur_loc - 1), 3)
IF PATINDEX('%[^0-9]%', @test) = 0 
BEGIN

SET @first = CAST(@test AS smallint)

-- Second Bloc
SET @last_loc = @cur_loc + 1 
SET @cur_loc = CHARINDEX('.', @AddrIp, @last_loc)

SET @test = LEFT(SUBSTRING(@AddrIp, @last_loc,

@cur_loc - @last_loc), 3)
IF PATINDEX('%[^0-9]%', @test) = 0 
BEGIN 
SET @second = CAST(@test AS smallint)


-- Troisième Bloc
SET @last_loc = @cur_loc + 1 
SET @cur_loc = CHARINDEX('.', @AddrIp, @last_loc)

SET @test = LEFT(SUBSTRING(@AddrIp, @last_loc,

@cur_loc - @last_loc), 3)
IF PATINDEX('%[^0-9]%', @test) = 0 
BEGIN

SET @third = CAST(@test AS smallint)

-- Quatrième Bloc
SET @last_loc = @cur_loc + 1 
SET @test = LEFT(SUBSTRING(@AddrIp, @last_loc,

LEN(@AddrIp)

- @last_loc + 1), 3)
IF PATINDEX('%[^0-9]%', @test) = 0 
BEGIN

SET @fourth = CAST(@test AS smallint)

END

END

END

END

-- Résultat
IF @first <= 255 
AND @second <= 255
AND @third <= 255 
AND @fourth <= 255 
BEGIN

IF @first <= 127 
SET @result = CAST(@first as int) * 0x1000000
+ CAST(@second as int) * 0x10000 + CAST(@third as int)


* 0x100 + CAST(@fourth as int)
ELSE 
SET @result = ( CAST(( @first & 0x7F ) as int) * 0x1000000
+ CAST(@second as int) * 0x10000 
+ CAST(@third as int) * 0x100
+ CAST(@fourth as int) ) | 0x80000000 
END

RETURN @result

END

GO

Langage : Python
Date ajout : 19/12/2007
Posté par 0x586e [Liste]
def ip2long(i):
    s = i.split('.')
    return (int(s[0]) << 24 | int(s[1]) << 16 | int(s[2]) << 8 | int(s[3]))
def long2ip(l):
    return str(int(l) >> 24)+'.'+str((int(l) >> 16)%256)+'.'+str((int(l) >> 8)%256)+'.'+str(int(l)%256)
# Affiche 2130706433
print ip2long('127.0.0.1')
# Affiche 127.0.0.1
print long2ip('2130706433')

Snippets en rapport avec : Ip, Convertir, Long, Iptolong, Longtoip



Codes sources en rapport avec : Ip, Convertir, Long, Iptolong, Longtoip

{Visual Basic, VB6, VB.NET, VB 2005} MASTERLOCATER.NET
Cette source vous donne quulque information regionnal a partir de votre addresse IP.utilisation des ...

{Visual Basic, VB6, VB.NET, VB 2005} CONVERTISSEUR COULEUR FORMAT LONG AU FORMAT RGB
Ce code permet d'obtenir ls trois composantes RGB à partir d'une couleur sélectionnée avec, par exem...

{Python} SCANNEUR D'IP21
Voilà, c'est un petit scanneur de pub, Il est en ligne de commande ce qui permet de l'utiliser en...

{C / C++ / C++.NET} CONVERTISSEUR / CRYPTEUR D'IP
Bonjour, J'ai vu plusieurs IP Crypteur sur le site mais... - Sur l'un, on doit tapez l'adresse...

{PHP} CHIFFRES EN LETTRES
cette source converti des chiffres en des chaines de caractère en toute lettre supporte jusqu'à 999...

{C / C++ / C++.NET} CRYPTEUR-DÉCRYPTEUR-IP
Logiciel qui pourra vous servir a crypter votre adresse IP et par la suite le décrypter avec l'app...

{Python} DIVISIONS AVEC PRÉCISION RÉGLABLE
Voici un petit programme qui vous permet d'avoir le résultat de divisions avec la précision que vous...

{C / C++ / C++.NET} ID3 TAG COVER ALBUM IMAGE
album art cover ajout pour mp3 choisi un dossier avec de la music mp3 si il y a un ou plusieur im...

{C / C++ / C++.NET} JEU PUISSANCE IV
Coder en langage C++, ce programme permet une fois lancer de jouer au puissance IV et ce en console....

{Python} SIMPLE COMPARATEUR IPV4 EN PYTHON
Comparaison de deux adresses IPv4 pour determiner si elles sont sur le meme sous reseau. Le script e...