Help With Splitting Strings (Java)

Started by
2 comments, last by WarmWaffles 16 years, 8 months ago
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
Advertisement
Google tells me about java.lang.String.split, and java.lang.Integer for splitting strings and parsing integers, respectively.

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.
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]

This topic is closed to new replies.

Advertisement