Creating an Inet4Address from a String for a SocketConnection

  • Context: Comp Sci 
  • Thread starter Thread starter 0rthodontist
  • Start date Start date
  • Tags Tags
    String
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 4K views
Messages
1,229
Reaction score
0
How do I make a SocketAddress that I can pass to a Socket so that I can connect to a computer whose IP address I have as a string? I think that want I want is an Inet4Address but Inet4Address has no constructor. SocketAddress says it is meant to be "subclassed" by a protocol-specific address type, but I don't know what they mean. Is there a factory class that will do this for me?

Edit: I made my own method to parse it into a byte[] but now it won't accept an InetAddress as a SocketAddress. An InetAddress is a SocketAddress though. And it won't let me cast it. What's the deal?

Edit: Never mind, an InetSocketAddress is a SocketAddress, an InetAddress isn't. I still would like to know if there is a built-in way to make an InetAddress from a string though. In Inet4Address it seems to suggest that there is, since it specifies the format of such a string.
 
Last edited:
Physics news on Phys.org
But I'm designing the program so the user inputs an IP address, not a name. Will getByName parse an IP address?
 
Last edited:
Oh, duh! Sorry. I was looking at the documentation but only at the short description, not at the longer explanation below. Thanks for your help.

Ah, here is a further problem: when I close my applet if I have a connection open it always generates an error on the console. Is there any way to make the applet close its own connections when terminated unexpectedly?
 
Last edited:
Thanks for your help so far. I have another question:

I'm adding a GUI to an existing program, written by someone else. This program has a bunch of different classes and spawns a new thread for each user who connects. What I'd like to do is have the GUI be 1 class, and let any other class call a method in the GUI (e.g. add a user name to the user list display) without me having to alter their constructors to explicitly pass them the GUI. I basically want the GUI to somehow be "global" over several classes. Is this possible? One klunky way I can think of is that I could set up the GUI as its own thread with a port and ServerSocket, and other classes communicate to it via the port.
 
Last edited: