I have a server program on my PC which is running and waiting for the Android client.
I set these in my Android code:
mHost = "127.168.1.1"; //or getLocalIpAddress()?
mPort = 5000;
mSocket = new Socket(mHost, mPort);
And have these permissions in the manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
When I try to connect to my PC, I get this logcat output:
10-08 19:18:40.970: E/ex closeInputOutput(8735): java.lang.NullPointerException
10-08 19:18:40.970: E/doInBackground Exception(8735): java.net.ConnectException: failed to connect to /127.168.1.1 (port 5000): connect failed: ECONNREFUSED (Connection refused)
I have a router, how can I connect to my PC to 127.168.1.1:5000?
edit:
public static final String getLocalIpAddress() {
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();
String ip4 = inetAddress.getHostAddress().toString();
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ip4)) {
Log.d(TAG, "getLocalIpAddress(): " + ip4);
return ip4;
}
}
}
}
catch (Exception e) {
Log.e(TAG, "ServerUtils: getLocalIpAddress(): " + e.getMessage());
}
return null;
}
this is my new Code, this return 192.168.1.104, wich is not working. with my ipconfig I get 192.168.1.102 (that is the correct.)
So in the last code what is wrong? How can I get the correct local IP?
It may be different in your LAN, but usually the address 192.168.1.1 is the router address (not the host address).
Confirm you host address by running the command:
at command prompt. The IPv4 address will be the host address and the Gateway address the router address. Be sure to use the correct address on both PC and device.
Note: You need to post the relevant part of your code, both on PC and device, if you want more precise help.
–EDITED–
IP address is like a home address, each device has his own. So when you run ipconfig on the windows machine you get the windows machine ip address. When you call the
getLocalIpAddress()on device you get the device IP address.If you want to connect from the device to the PC, you need to:
192.168.1.102(pc IP address) at port5000