asd
Alejandro Acuña
2024-09-16 816cb391a192e357426312ab8e591fd49d1d242e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package art.servers.types;
 
public class IPv4 
{
    public static long toLong(int mask) throws Exception
    {
        long result = 0xFFFFFFFFL;
        
        for(int i=0; i<(32-mask); i++)
        {
            result = result ^ ((long)1 << i);
        }
        
        return result;
    }
    
    
    public static long toLong(String ipAddress) throws Exception
    {
        if (ipAddress == null || ipAddress.isEmpty()) throw new Exception();
        String[] octets = ipAddress.split(java.util.regex.Pattern.quote("."));
        if (octets.length != 4) throw new Exception();
        long ip = 0;
        for (int i = 3; i >= 0; i--) 
        {
            long octet = Long.parseLong(octets[3 - i]);
            if (octet > 255 || octet < 0) throw new Exception();
            ip |= octet << (i * 8);
        }
        return ip;
    }
 
    
 
    public static String toString (long ip) throws Exception 
    {
        if (ip > 4294967295l || ip < 0) throw new Exception();
        StringBuilder ipAddress = new StringBuilder();
        for (int i = 3; i >= 0; i--) 
        {
            int shift = i * 8;
            ipAddress.append((ip & (0xff << shift)) >> shift);
            if (i > 0)  ipAddress.append(".");
        }
        return ipAddress.toString();
    }
}