• Post Reply Bookmark Topic Watch Topic
  • New Topic

Program that expands IP from short to full length  RSS feed

 
Andrew Sy
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I'm trying to write a program that can convert an IP from short to full address by filling zeros at the beginning.

Input:

2001:db8:3c4d:15::1a2f:1a2b
FFED::A98:3210:4562
a34:1234:00:555:99:0:000:1

Output:
2001:0db8:3c4d:0015:0000:0000:1a2f:1a2b
FFED:0000:0000:0000:0000:0A98:3210:4562
0a34:1234:0000:0555:0099:0000:0000:0001

I tried using regular expressions to find a string match. However, I find it challenging as it seems like I need to hard code for all possible combinations.
Im just wondering if there's a way you can help make my code more efficient and simpler.

I also saw this post regarding IP expand but Im not sure how to implement it to my code..
Hopefully someone can fix my code.



 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

I'd do something like the following, in pseudo code, and assuming the IP address is valid:
(Hmm, this is actually what Dhaval J. Patel wrote as well.)

If you want to validate that the IP address is valid yourself, you must make sure that:
- parts.length <= 8
- each part is valid (1 to 4 occurrences of 0-9A-Fa-f)
- there is at most one empty part (only one occurrence of :: is allowed)
 
Andrew Sy
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Rob, thanks for your reply Sorry Im not quite familiar with left pad parts with zeroes, and join parts with separator. I know it's a pseudo code, but I'm just wondering if you a sample running code that I can compile and test with

Sorry, Im still fairly new to java and I'm not that familiar of some functions/utils..
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andrew Sy wrote:Sorry Im not quite familiar with left pad parts with zeroes, and join parts with separator.


Padding zeros to the left can be done by simply checking the length of the string and concatenating some zeros to the left. Or you can use the Formatter class to help too -- but it is probably not necessary, as the methods of the String class should be sufficient. As for joining the strings, you can use a loop and concatenating the strings. Or you can use the StringBuilder class to help too.

Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!