Reputation: 61
I'm trying to write a program in Java that will take an IP address and convert to binary.
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!");
}
}
}
Upvotes: 3
Views: 16836
Reputation: 4605
The open-source IPAddress Java library can 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.
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
Upvotes: 0
Reputation: 1140
If you want to avoid name resolution, you can use the following code that converts an IPv4 address string to a byte array:
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();
}
Upvotes: 0
Reputation: 236004
Building on jtahlborn' answer:
byte[] bytes = InetAddress.getByName(data_in).getAddress();
data_out = new BigInteger(1, bytes).toString(2);
Now data_out
contains the IP address as a binary number.
Upvotes: 7
Reputation: 1767
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
1010
1010
10010110
1
Upvotes: 2
Reputation: 53694
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.
Upvotes: 4