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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9900284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:49:01  来源:igfitidea点击:

Converting an IP address to binary values (Java)

javabinaryip-addressconverter

提问by jerms246

I'm trying to write a program in Java that will take an IP address and convert to binary.

我正在尝试用 Java 编写一个程序,该程序将获取 IP 地址并转换为二进制文件。

Here is what I have so far:

这是我到目前为止所拥有的:

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

        }
    }
}

回答by óscar López

Building on jtahlborn' answer:

基于 jtahlborn 的回答:

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

Now data_outcontains the IP address as a binary number.

现在data_out包含二进制数形式的 IP 地址。

回答by jtahlborn

you can use InetAddress to parse the textual representation and convert to a byte[]. you can use BigDecimal to convert a byte[] to a big integer.

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

回答by Dan675

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

so for input 10.10.150.1 output will be

所以对于输入 10.10.150.1 输出将是

1010

1010

1010

1010

10010110

10010110

1

1

回答by Michael Yakobi

If you want to avoid name resolution, you can use the following code that converts an IPv4 address string to a byte array:

如果要避免名称解析,可以使用以下代码将 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();
}

回答by Sean F

The open-source IPAddress Java librarycan do this for you. It can parse various IP address formats, including either IPv4 or IPv6. Disclaimer: I am the project manager of the IPAddress library.

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

Here is sample code similar to yours:

这是类似于您的示例代码:

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) {}
}

Example usage:

用法示例:

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