Cannot connect using hostname from an Android device - java

I am trying to connect from my android device to a linux PC using TCP protocol.
Both devices are on the same network.
When I use a simple java code like this on my other PC on the same network, it works and I get an output
class Server {
public static void main ( String[] args ) throws IOException
{
String hostname = "MY_COMPUTER_NAME";
try
{
InetAddress ipaddress = InetAddress.getByName(hostname);
System.out.println("IP address: " + ipaddress.getHostAddress());
}
catch ( UnknownHostException e )
{
System.out.println("Could not find IP address for: " + hostname);
}
}
}
Output:
IP address: 192.168.1.3
When I use this code to connect to a socket on my android phone, it just doesn't work. The handler also updates another TextView for debugging. When I replace MY_COMPUTER_NAME with the actual IP that I can see on my router settings, everything works, the socket is created and the TextView is updated.
//Some variables
String hostname = "MY_COMPUTER_NAME";
private static final int SERVERPORT = 5001;
InetAddress ipaddress = null;
String address = null;
#Override
public void run() {
while(true){
try {
ipaddress = InetAddress.getByName(hostname);
address = ipaddress.getHostAddress();
socket = new Socket(ipaddress, SERVERPORT);
myHandler.post(updateRunnable);
break;
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
What could be the problem, and what am I missing? Thanks.

I think Android has problems with NetBIOS names, but can lookup names that are registered at the DNS Server. see here: Host is unresolved in LAN

Related

How to get the local computer's IP address, even when the computer is connected to a VPN?

I'm writing a java program which needs to get the computer's IP address(not the Internet IP, just the local one). The program worked, but when I connected to my VPN server, I noticed that the IP address I was getting was invalid. This is the code I'm using:
public static String getIP() {
try (final DatagramSocket socket = new DatagramSocket()) {
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
return socket.getLocalAddress().getHostAddress();
} catch (IOException ex) {
ErrorHandler.handle(ex);
return "";
}
}

Java - Which IP to use for the ServerSocket and Socket classes?

I just recently found the ServerSocket and Socket class found in the Java library and so I wanted to make a simple messaging app. The purpose of the app is to be able to communicate with someone on a different network than mine (I am the server side and have my own client side).
Here is the Messenger_Server.java's connecting method
public static void main (String [] args)throws IOException{
InetAddress ip;
try{
final int PORT = 444;
ip = InetAddress.getLocalHost();
ServerSocket server = new ServerSocket(PORT);
System.out.println("Waiting for clients...");
System.out.println(server.getInetAddress() + " " + ip.getHostAddress());
while(true){
Socket sock = server.accept();
connectionArray.add(sock);
System.out.println("Client connected from " + sock.getLocalAddress().getHostName());
addUserName(sock);
Messenger_Server_Return chat = new Messenger_Server_Return(sock);
Thread X = new Thread(chat);
X.start();
}
} catch(Exception e) {
e.printStackTrace();
}
}
Here is the client's connecting method from Messenger_Client.java
public static void connect(){
try{
final int PORT = 444;
// the ip below is the one i get as my ipv4
Socket sock = new Socket ("10.122.***.***",PORT);
System.out.println("you be connected to: " + InetAddress.getByAddress(InetAddress.getLocalHost().getAddress()));
chatClient = new Messenger_Client(sock);
PrintWriter out = new PrintWriter(sock.getOutputStream());
out.println(userName);
out.flush();
Thread X = new Thread(chatClient);
X.start();
}catch (Exception X){
X.printStackTrace();
JOptionPane.showMessageDialog(null, "Server not responding.");
System.exit(0);
}
}
So I gave the client side of the program to my friend and he said the host could not be found. Which IP should I use so my friend can connect to my ServerSocket, and could there be anything limiting my friend from connecting to me?

Java - TCP socket only connects in LAN

I have created a small TCP server but it only connects to other computers on my LAN. I did forward the port but it is still not working.
connection method:
private boolean connect(){
try {
socket = new Socket(InetAddress.getByName(ip), port);
System.out.println("socket created");
dataOutput = new DataOutputStream(socket.getOutputStream());
dataInput = new DataInputStream(socket.getInputStream());
accepted = true;
} catch (IOException e) {
System.out.println("Unable to connect to the server");
return false;
}
System.out.println("Successfully connected to the server.");
return true;
}
listen method:
private void listenForServerRequest(){
Socket socket = null;
try{
socket = serverSocket.accept();
dataOutput = new DataOutputStream(socket.getOutputStream());
dataInput = new DataInputStream(socket.getInputStream());
accepted = true;
System.out.println("client joined");
}catch(IOException e){
e.printStackTrace();
}
}
opening the server:
private void initializeServer(){
try{
serverSocket = new ServerSocket(port,8,InetAddress.getByName(ip));
}
catch(Exception e){
e.printStackTrace();
}
}
It appears as if you're supplying an IP address to InetAddress.getByName(). It requires a host name. Specifically, it needs the host name corresponding to the network that the port is forwarded to. For example, if you're forwarding to your computer's (internal) ip address (say, 192.168.1.10), then it needs the host name that corresponds to that address (for example mycomputer.local). Java needs that host name to know what interface it should listen on. I'm surprised it worked at all.
If you do want to supply the IP address and not the host name, use InetAddress.getByAddress(byte[] addr) instead:
byte[] addr = new byte[4];
addr[0] = 192;
addr[1] = 168;
addr[2] = 1;
addr[3] = 10;
...
serverSocket = new ServerSocket(port,8,InetAddress.getByAddress(addr));

Android Java Server Socket does not connect

I am writing an app which needs to receive a string from a server. The following code works if the IP Adress connected to is "127.0.0.1" (The Client and the server are on the same phone, just for testing purpose), but not if it is the "real" IP Adress of the phone.
Server:
ServerSocket echoServer = null;
String line;
DataInputStream is;
PrintStream os;
Socket clientSocket = null;
// Try to open a server socket on port 9999
try {
echoServer = new ServerSocket(1109);
} catch (IOException e) {
System.out.println(e);
}
// Create a socket object from the ServerSocket to listen and
// accept
// connections.
// Open input and output streams
try {
clientSocket = echoServer.accept();
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
// As long as we receive data, echo that data back to the
// client.
os.println("Das ist ein Test immernoch");
publish("Fertig");
} catch (IOException e) {
publish("Fertig");
} catch (Exception e) {
publish("Fertig");
}
Client:
Socket smtpSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
try {
smtpSocket = new Socket();
smtpSocket.connect(new InetSocketAddress("46.114.153.58", 1109), 10000); //That is the critcal line, if the IP is "127.0.0.1" everything works perfectly fine
os = new DataOutputStream(smtpSocket.getOutputStream());
is = new DataInputStream(smtpSocket.getInputStream());
} catch (UnknownHostException e) {
return "Fehler";
} catch (IOException e) {
return "Fehler";
}
if (smtpSocket != null && os != null && is != null) {
try {
os.writeBytes("HELO\n");
String s = is.readLine();
os.close();
is.close();
smtpSocket.close();
return s;
} catch (UnknownHostException e) {
//System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
//System.err.println("IOException: " + e);
}
}
return "Fehler";
}
EDIT: Hence this is an app for a mobile device, there is no router I can configure.
Add this to your code
if (Build.VERSION.SDK_INT >= 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
You might have to forward the port you are using on your router if you are planning on using ServerSocket with external connections.
If this is the ip address of your router and you are connecting your android mobile to the router through wifi , then you have to port forward the port 1109 in your router to your mobile.
If this is the ip address of your android mobile connected through data connection , then there will be some restrictions on your data provider blocking ports for security .
46.114.153.58 is this a static ip address or dynamic ?
If its a dynamic ip address , first check the availability of the ip address by pinging it.

Establishing connecting using Java RMI

I'm writing a program that connects Client machine to Server using RMI and so far I keep getting java.net.ConnectException: Connection refused.
Here is my code;
Interface
public interface ServerInterface extends Remote
{
public String getMessage() throws RemoteException;
}
Server
public class Server extends UnicastRemoteObject implements ServerInterface
{
int portNumber = 7776;
String ipAddress;
Registry registry;
public Server() throws RemoteException
{
try
{
ipAddress = "192.168.0.104";
System.out.println("IP Address: " + ipAddress + " Port Number: " + portNumber);
registry = LocateRegistry.getRegistry();
registry.rebind("ServerFour", this);
}
catch (RemoteException e)
{
System.out.println("Remote Exception Error");
}
}
public String getMessage() throws RemoteException
{
String output = "Connected to Server";
return output;
}
public static void main(String args[])
{
try
{
Server server = new Server();
}
catch (RemoteException ex)
{
System.out.println("Remote Exception in Main");
}
}
}
Client
public class Client
{
public static void main(String[] args) throws NumberFormatException, RemoteException, NotBoundException
{
try
{
ServerInterface server;
Registry registry;
String serverAddress = "192.168.0.104";
String serverPort = "7776";
registry = LocateRegistry.getRegistry(serverAddress, Integer.valueOf(serverPort));
server = (ServerInterface)(registry.lookup("ServerFour"));
String serverMessage = server.getMessage();
System.out.println("Servers Message: " + serverMessage);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
For now I just want Client to call on the method in the ServerInterface and print out its message, but I can't seem to get it to work. I get the Exception message shown above when I start the Client.
When I start the Server it returns this:
IP Address: client4/127.0.1.1 Port Number: 1234
Update:
I've changed the port number to 7776
Ran rmiregistry 7776 &
This is what I get when I start Server and run netstat -anpt
http://i.imgur.com/GXnnG.png
Now on the Client side I'm getting this:
http://i.imgur.com/aBvW3.png
It seems the RMI Registry is bound to localhost (cf. 127.0.0.1 - I assume the 127.0.1.1 is a typo?), yet try to contact it from the client on 192.168.0.104 - that won't work, since nothing presumably is listening on that interface! Try changing the client serverAddress to 127.0.0.1 instead.
The command netstat -anpt (or on Windows: netstat -anbt) is your friend when you want to see what processes are bound on which interfaces (the t is for TCP by the way).
This is the way to bind the Registry to a specific IP (eg. localhost),
registry =
LocateRegistry.
createRegistry( portNumber ,
new RMIClientSocketFactory()
{
#Override
public Socket createSocket( String host, int port ) throws IOException
{
return new Socket( "127.0.0.1" , port );
}
} ,
new RMIServerSocketFactory()
{
#Override
public ServerSocket createServerSocket( int port ) throws IOException
{
return new ServerSocket( port , 0 , InetAddress.getByName( "localhost") );
}
} );
Cheers,

Categories

Resources