Sign in to follow this  
WarmWaffles

Help With Splitting Strings (Java)

Recommended Posts

Hi guys, My google fu isn't strong today, and I just can't find any helpful information on how to split a string in java, or rather an IP Address. I have been programming in Java for about 5 months now and I happened to miss the day they talked about parsing strings in my class at high school.
if (event == joinG)
{
	msgDisplay = JOptionPane.showInputDialog(
			"Server IP Address? \n (e.g. 127.0.0.1)", "127.0.0.1"
			);
			
	create = false;
	join = true;
}



Now what needs to be done is that the string that it out puts needs to be split and put into byte form, something like this. (I am currently networking and the way I test is over Hamachii with my friends)
byte[] addr = { (byte) 5, (byte) 154, (byte) 65, (byte) 219 };



Granted something so simple would be so complicated in my mind. I think I also want to have some sort of IP Address checking to make sure the user wasn't a ditz on a keyboard (e.g. "0.0.0.0") Any help or pointing me towards a tutorial that does what I need, please let me know

Share this post


Link to post
Share on other sites

String s = "127.0.0.1";

try {
InetAddress addr = InetAddress.getByName( s );

byte[] elements = addr.getAddress();
// elements contains individual values that make up the address
} catch (UnknownHostException e ) {
// invalid
}



This works also if s contains a DNS name ("www.gamedev.net"), in which case it'll be resolved and checked for validity.

Share this post


Link to post
Share on other sites
Very interesting Antheus and very helpful

EDIT:
Wow that was a ton of help and simplified a ton of code to just few lines. Thank you Antheus you have been rated up (^_^)

[Edited by - WarmWaffles on August 13, 2007 12:50:57 PM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this