将IP地址转换为二进制值(Java)

时间:2012-03-28 02:16:46

标签: java binary ip-address converter

我试图用Java编写一个程序来获取IP地址并转换为二进制文件。

这是我到目前为止所做的:

import java.util.Scanner;

public class IpConverter{

public static void main (String[]args)
{

    int result;

    String data_in;

    int data_out;

        Scanner scan = new Scanner(System.in);

        try
        {
            System.out.print("Enter an IP address: ");
            data_in = scan.next();

            data_out = Integer.parseInt(data_in, 10);
            System.out.println (data_in + "is equivalent to" + data_out);
        }
        catch (NumberFormatException nfe){
            System.out.println("Wrong data type!");

        }
    }
}

5 个答案:

答案 0 :(得分:7)

建立在jtahlborn的回答:

byte[] bytes = InetAddress.getByName(data_in).getAddress();
data_out = new BigInteger(1, bytes).toString(2);

现在data_out包含IP地址作为二进制数。

答案 1 :(得分:4)

您可以使用InetAddress来解析文本表示并转换为byte []。你可以使用BigDecimal将byte []转换为一个大整数。

答案 2 :(得分:2)

Scanner in = new Scanner(System.in);
System.out.println("Please enter an IP Address.");
String ip = in.nextLine();
String[] octetArray = ip.split("\\.");
for (String string : octetArray){
    int octet = Integer.parseInt(string);
    String binaryOctet = Integer.toBinaryString(octet);
    System.out.println(binaryOctet);
}

因此输入10.10.150.1 输出将是

1010

1010

10010110

1

答案 3 :(得分:0)

如果要避免名称解析,可以使用以下代码将IPv4地址字符串转换为字节数组:

String[] octetArray = ipAddressStr.split("\\.");
assert octetArray.length == 4;
byte[] ipAddressBytes = new byte[4];
for (int i = 0; i < 4; ++i) {
    ipAddressBytes[i] = Integer.valueOf(octetArray[i]).byteValue();
}

答案 4 :(得分:0)

open-source IPAddress Java library可以为您做到这一点。它可以解析各种IP地址格式,包括IPv4或IPv6。免责声明:我是IPAddress库的项目经理。

以下是与您的示例代码相似的示例代码:

public static void main(String[] args) {
    try(Scanner scan = new Scanner(System.in)) {
        System.out.print("Enter IP addresses: ");
        while(true) {
            String data_in = scan.next();
            IPAddressString string = new IPAddressString(data_in);
            IPAddress addr = string.toAddress();
            System.out.println(addr + " is equivalent to " + addr.toBinaryString());
        }
    } catch (AddressStringException e){
        System.out.println("invalid format: " + e.getMessage());
    } catch(NoSuchElementException e) {}
}

用法示例:

Enter IP addresses: 1.2.3.4 a:b:c:d:e:f:a:b
1.2.3.4 is equivalent to 00000001000000100000001100000100
a:b:c:d:e:f:a:b is equivalent to 00000000000010100000000000001011000000000000110000000000000011010000000000001110000000000000111100000000000010100000000000001011