views:

1278

answers:

2

I am trying to open a Socket on Android but everytime I try I keep getting connection refused error no matter what way I try.

The error happens on the following line of code where I try to create the connection.


Socket socket = new Socket(getLocalIpAddressString(), 8008);

The following is the method I use to get the local ip address:


public static String getLocalIpAddressString() {
 try {
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
         NetworkInterface intf = en.nextElement();
         for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
             InetAddress inetAddress = enumIpAddr.nextElement();
             if (!inetAddress.isLoopbackAddress()) {
                 return inetAddress.getHostAddress().toString();
             }
         }
     }
 } catch (SocketException ex) {
     Log.e("IPADDRESS", ex.toString());
 }
 return null;

}


And the error I get is:


WARN/System.err(3574): java.net.ConnectException: /192.168.2.163:8008 - Connection refused
WARN/System.err(3574):     at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:237)
WARN/System.err(3574):     at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:199)
WARN/System.err(3574):     at java.net.Socket.startupSocket(Socket.java:734)
WARN/System.err(3574):     at java.net.Socket.<init>(Socket.java:157)
WARN/System.err(3574):     at com.networks.phone.engine.SIPEngine.rtpTest(SIPEngine.java:1444)

I presume its an error with my Ipaddress and or port? But can anyone point me in the right direction as to what might be the cause?

+1  A: 

From your code, I assume you're trying to open a socket connection from an Android app to the same Android device.

Being based on Linux and all, maybe Android has some kind of firewall or connection rules that prevent your socket to connect successfully. Check the documentation, it may be an Android configuration problem and not a Java problem.

Olivier Croisier
Maybe, connecting to another device might be a better idea?
Donal Rafferty
A: 

Hi,I have the same problem with you now. On the Android emulator,the getLocalIpAddressString() function returns an ip address like 10.0.2.15.As you konw,it is a private ip. We need to set a public ip for Android server we create,so how could we get the public ip of Android? And how do you solve the problem when the connection is refused? Thank you for your help.

Probably best to make this a question of its own
Donal Rafferty