I am working on an Android Studio project with several activities. I am currently trying to read the output from a Java Servlet on localhost but it seems to be crashing due to a socket permission.
I’ve made a new project, used the exact same code and worked perfectly. So I dont understand why is not willing to work on my project.
public class LoginActivity extends AppCompatActivity {
String apiUrl = "http://10.0.2.2:8080/ProyectService/Servlet?action=login";
EditText username;
EditText password;
AlertDialog dialog;
Usuario session;
@Override
public void onCreate(Bundle savedInstanceState) {
// Inicializacion de ventana
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
// Inicializacion de componentes
username = findViewById(R.id.username);
password = findViewById(R.id.password);
// Inicializacion de funcionalidad de botones
Button button= (Button) findViewById(R.id.login);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
UserLoginTask mAuthTask = new UserLoginTask();
mAuthTask.execute();
}
});
password = findViewById(R.id.password);
createAlertDialog("Usuario o Contraseña Incorrectos");
}
private void createAlertDialog(String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setTitle("Error");
dialog = builder.create();
}
// ASYNCRONUS NETWORK PROCESS
public class UserLoginTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
// implement API in background and store the response in current variable
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(apiUrl);
System.out.println(apiUrl);
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
current += (char) data;
data = isw.read();
//System.out.print(current);
}
System.out.print(current);
// return the data to onPostExecute method
return current;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}
}
protected void onPostExecute(String success) {
Log.i(success, "");
//attemptLogin();
}
}
I Expect it to read the data but it crashes at this line:
InputStream in = urlConnection.getInputStream();
This is the error output:
java.net.SocketException: socket failed: EPERM (Operation not permitted)
at java.net.Socket.createImpl(Socket.java:492)
at java.net.Socket.getImpl(Socket.java:552)
at java.net.Socket.setSoTimeout(Socket.java:1180)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:114)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:93)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
asked May 23, 2019 at 1:02
Aaron VillalobosAaron Villalobos
10.3k3 gold badges8 silver badges9 bronze badges
Your app needs additional permissions and/or to be reinstalled.
Add additional permissions to AndroidManifest.xml within the <manifest> section:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
To reinstall, uninstall the app from the emulator or physical connected device and then run it again. (If adding permissions, make sure to reinstall afterwards.)
Dave
11.2k5 gold badges34 silver badges46 bronze badges
answered May 23, 2019 at 2:36
Aaron VillalobosAaron Villalobos
10.3k3 gold badges8 silver badges9 bronze badges
18
Just uninstall the app from the emulator then run again and it’ll work. I had the same issue
To uninstall the app run your project when «the application had stopped» message appear click «app info» then uninstall.
Reid
6321 gold badge8 silver badges22 bronze badges
answered Nov 10, 2019 at 20:04
John AlexanderJohn Alexander
1,0611 gold badge5 silver badges3 bronze badges
4
First of all you need change your android manifest .xml
But after this action you must uninstall application and run it again.
https://developer.android.com/training/basics/network-ops/connecting
and code here:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in AndroidManifest.xml
answered Sep 2, 2019 at 19:36
Archil LabadzeArchil Labadze
3,8674 gold badges25 silver badges42 bronze badges
3
If you forgot to add <uses-permission android:name="android.permission.INTERNET" /> to your Manifest.xml, do it now
If you already added it but the error persists, uninstall the app first then run i again.
More often than not I run into the same issue because I forgot <uses-permission android:name="android.permission.INTERNET" /> in my first installation.
The OS thought the app doesn’t need Internet permission (which is dumb IMO) and would not check any permission update to the app (which is even dumber IMO).
The only way to tell the Android OS to check your updated permission requests is to uninstall the app first before installing again.
I think neither
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />- nor
android:usesCleartextTraffic="true"
really matters here
answered Jan 5, 2021 at 16:52
4
I had to uninstall the app from the emulator and then everything started to work. I just needed the folowing permission on the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
answered Nov 7, 2019 at 13:21
- Add ACCESS_NETWORK_STATE permission in manifest
- Reinstallation emulator
answered Dec 3, 2019 at 12:05
AK IJAK IJ
4824 silver badges10 bronze badges
0
I had the same issue in android emulator, even after adding
<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" />
and
android:usesCleartextTraffic="true"
and reinstalling the app still had the issue on my emulator.
AVD Manager -> Right click -> Cold Boot now
solved my issue, looks like if we ran the app initially without adding internet permissions / clearTextTraffic we might need to cold boot as it store some cache.
answered Dec 3, 2020 at 14:25
1
Set android:usesCleartextTraffic="true" in the manifest file.
Add the permission INTERNET.
Uninstall app and then install again.
answered May 1, 2020 at 23:02
GilbertGilbert
2,28523 silver badges28 bronze badges
If you are using a localhost server on your Mac then use the local IP address that is assigned for your machine as your API address. i.e. 192.168.x.x (find it in Settings -> Network) not localhost nor 127.0.0.1.
As they mentioned above, uninstall the app and then put these tags in your manifest:
in the application section:
android:usesCleartextTraffic="true"
Then in your manifest section:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.a.myapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
answered Apr 12, 2021 at 2:15
ChosenChosen
8392 gold badges9 silver badges20 bronze badges
Working solution.
- check if you have INTERNET permission and ACCESS_NETWORK_STATE permission, if not add these.
- uninstall the app and install again. If not try in different device. It will work 100%. I face same issue and solved this by using these steps.
answered Oct 7, 2021 at 11:30
sudhanshusudhanshu
3891 gold badge4 silver badges11 bronze badges
Set android:usesCleartextTraffic=»true» in the manifest file. Add the permission INTERNET. Uninstall app and then install again.its work to me
answered Nov 28, 2020 at 18:56
If anyone still has this issue I encountered it when I used VPN and tried to connect to wifi while cellular was on. I was using Anyconnect VPN client.
Solution is to enable the allow bypass that will let you bind a socket to a specific network if this is what you are looking for.
AnyConnect only uses allowBypass if it’s configured in its managed restrictions (by EMM), via this key: vpn_connection_allow_bypass.
answered Nov 27, 2019 at 15:50
ovidiurovidiur
3282 silver badges9 bronze badges
I had to delete this
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
and keep this
android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" />
answered Oct 20, 2020 at 1:59
khoanekhoane
311 silver badge4 bronze badges
0
I am a little late to this but I encountered this problem and I found out that android:usesCleartextTraffic requires minimum API version of 23. Therefore, in the module gradle build file, switch the minimum version to 23 and it should work.
Dharman♦
29.3k21 gold badges80 silver badges131 bronze badges
answered Aug 3, 2021 at 11:21
Share this post and Earn Free Points!
A java.net.SocketException: socket failed: EPERM (Operation not permitted) error can occur in Java when a program attempts to create a new socket, but the operation is not allowed due to insufficient permissions. This can happen for a number of reasons, including:
- The program does not have the necessary permissions to create a socket.
- The system has reached the maximum number of sockets allowed.
- There is a problem with the network configuration or firewall settings that is preventing the creation of a new socket.
Table of Contents
Introduction
In Java, a Socket is a endpoint for sending or receiving data across a computer network. It can be used to establish a connection to a remote host and send or receive data over the network.
A Socket is created using the Java.net.Socket class. It takes two arguments: the IP address of the remote host and the port number on the remote host to which you want to connect. Here is an example of how to create a Socket in Java:
import java.net.Socket;
String host = "www.example.com";
int port = 80;
try {
Socket socket = new Socket(host, port);
} catch (IOException e) {
System.err.println("Could not connect to the host: " + host);
}
Once you have a Socket object, you can use it to send and receive data over the network. For example, you can use the getInputStream and getOutputStream methods to get InputStream and OutputStream objects, respectively, which you can use to read from and write to the socket.
I hope this helps! Let me know if you have any other questions about sockets in Java.
Error Troubleshooting
To troubleshoot this error, you can try the following steps:
- Check that the program has the necessary permissions to create a socket. Depending on the operating system and the security policies in place, you may need to run the program as an administrator or with special privileges to create a socket.
- Check the system’s maximum number of sockets allowed. This can vary depending on the system configuration, but if the system has reached the maximum number of sockets, you may need to close some existing sockets or increase the maximum number of sockets allowed.
- Check the network configuration and firewall settings. Make sure that the program is allowed to access the network and create sockets, and that there are no restrictions or rules that are preventing the creation of a new socket.
If these steps do not help, you may need to consult the Java documentation or seek assistance from a Java developer or support team to further diagnose and resolve the issue.
Reason 1 -> java.net.socketexception: socket failed: eperm operation not permitted
[ socket failed EPERM Operation not permitted ] The first place to look for the cause may be to check the file AndroidManifest.xml. Make sure you add permission:
java.net.socketexception: socket failed: eperm (operation not permitted)
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Reason 2 – java.net.socketexception: socket failed: eperm (operation not permitted)
If you still get this error despite adding the above permissions, then uninstall the application from Emulator and then run again the application from Android Studio.
What is Android Studio Emulator?
The Android Emulator simulates Android devices on your PC, allowing you to test your app on a variety of devices and API levels without having to own each one.
The emulator simulates practically every feature of a real Android device. You may simulate incoming phone calls and SMS messages, set the device’s location, test different network speeds, rotate and test other hardware sensors, and access the Google Play Store, among other things.
Testing your software on the emulator is in some ways faster and easier than doing it on an actual device. For example, you can transfer data to the emulator faster than you can to a USB-connected device.
The emulator has pre-configured settings for a variety of Android phones, tablets, Wear OS, and Android TV devices.
The emulator can be used manually via the graphical user interface or programmatically via the command line and emulator console. See Comparison of Android Emulator Tools for a comparison of the capabilities offered through each interface.
Summary
I hope that now the following error: java.net.SocketException: socket failed: EPERM (Operation not permitted) is not a trouble for you and you can easily handle it!
Could You Please Share This Post?
I appreciate It And Thank YOU! :)
Have A Nice Day!
Im getting this error: «com.amazonaws.AmazonClientException: Unable to execute HTTP request: socket failed: EPERM (Operation not permitted)» when trying to upload an image (jpeg) file to an s3 bucket. The bucket is set up, public, and i managed to upload to it using javascript… i also checked and i have all the required permissions, here they are:
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»/
uses-permission android:name=»android.permission.READ_EXTERNAL_STORAGE» /
uses-permission android:name=»android.permission.CAMERA»/
uses-permission android:name=»android.permission.ACCESS_FINE_LOCATION» /
uses-permission android:name=»android.permission.VIBRATE» /
(some of these are for other things)
Here is the code:
public void UploadImage(String imgUri)
{
File file = new File(imgUri.substring(6)); //this removes some junk, the uri is just a path (that i checked is correct and works)
CognitoCachingCredentialsProvider credentialsProvider;
credentialsProvider = new CognitoCachingCredentialsProvider(
getApplicationContext(),
"CENSORED", // Identity Pool ID
Regions.EU_WEST_2 // Region
);
AmazonS3 s3 = new AmazonS3Client(credentialsProvider);
TransferUtility transferUtility = new TransferUtility(s3, getApplicationContext());
TransferObserver observer = transferUtility.upload(
"icuimages", //this is the bucket name on S3
file.getName(),
file,
CannedAccessControlList.PublicRead //to make the file public
);
observer.setTransferListener(new TransferListener() {
@Override
public void onStateChanged(int id, TransferState state) {
if (state.equals(TransferState.COMPLETED)) {
Toast.makeText(getApplicationContext(),"Upload Successful",Toast.LENGTH_LONG).show();
} else if (state.equals(TransferState.FAILED)) {
Toast.makeText(getApplicationContext(),"Failed to upload",Toast.LENGTH_LONG).show();
}
}
@Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) { }
@Override
public void onError(int id, Exception ex) { }
});
}
it was made according to this
here is the full error log:
2019-08-06 12:40:44.790 5220-5877/ysb.softwere.icu D/UploadTask: Failed to upload: 3 due to Unable to execute HTTP request: socket failed: EPERM (Operation not permitted)
com.amazonaws.AmazonClientException: Unable to execute HTTP request: socket failed: EPERM (Operation not permitted)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:441)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.invoke(AmazonCognitoIdentityClient.java:566)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.getId(AmazonCognitoIdentityClient.java:448)
at com.amazonaws.auth.AWSAbstractCognitoIdentityProvider.getIdentityId(AWSAbstractCognitoIdentityProvider.java:172)
at com.amazonaws.auth.AWSEnhancedCognitoIdentityProvider.refresh(AWSEnhancedCognitoIdentityProvider.java:76)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:678)
at com.amazonaws.auth.CognitoCredentialsProvider.getCredentials(CognitoCredentialsProvider.java:465)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.getCredentials(CognitoCachingCredentialsProvider.java:485)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.getCredentials(CognitoCachingCredentialsProvider.java:77)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4653)
at com.amazonaws.services.s3.AmazonS3Client.getBucketRegionViaHeadRequest(AmazonS3Client.java:5430)
at com.amazonaws.services.s3.AmazonS3Client.fetchRegionFromCache(AmazonS3Client.java:5405)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4650)
at com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1752)
at com.amazonaws.mobileconnectors.s3.transferutility.UploadTask.uploadSinglePartAndWaitForCompletion(UploadTask.java:219)
at com.amazonaws.mobileconnectors.s3.transferutility.UploadTask.call(UploadTask.java:93)
at com.amazonaws.mobileconnectors.s3.transferutility.UploadTask.call(UploadTask.java:49)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.net.SocketException: socket failed: EPERM (Operation not permitted)
at java.net.Socket.createImpl(Socket.java:492)
at java.net.Socket.getImpl(Socket.java:552)
at java.net.Socket.setSoTimeout(Socket.java:1180)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:262)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:219)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:30)
at com.amazonaws.http.UrlHttpClient.writeContentToConnection(UrlHttpClient.java:162)
at com.amazonaws.http.UrlHttpClient.execute(UrlHttpClient.java:75)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:371)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:212)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.invoke(AmazonCognitoIdentityClient.java:566)
at com.amazonaws.services.cognitoidentity.AmazonCognitoIdentityClient.getId(AmazonCognitoIdentityClient.java:448)
at com.amazonaws.auth.AWSAbstractCognitoIdentityProvider.getIdentityId(AWSAbstractCognitoIdentityProvider.java:172)
at com.amazonaws.auth.AWSEnhancedCognitoIdentityProvider.refresh(AWSEnhancedCognitoIdentityProvider.java:76)
at com.amazonaws.auth.CognitoCredentialsProvider.startSession(CognitoCredentialsProvider.java:678)
at com.amazonaws.auth.CognitoCredentialsProvider.getCredentials(CognitoCredentialsProvider.java:465)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.getCredentials(CognitoCachingCredentialsProvider.java:485)
at com.amazonaws.auth.CognitoCachingCredentialsProvider.getCredentials(CognitoCachingCredentialsProvider.java:77)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4653)
at com.amazonaws.services.s3.AmazonS3Client.getBucketRegionViaHeadRequest(AmazonS3Client.java:5430)
at com.amazonaws.services.s3.AmazonS3Client.fetchRegionFromCache(AmazonS3Client.java:5405)
at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4650)
at com.amazonaws.services.s3.AmazonS3Client.putObject(AmazonS3Client.java:1752)
at com.amazonaws.mobileconnectors.s3.transferutility.UploadTask.uploadSinglePartAndWaitForCompletion(UploadTask.java:219)
at com.amazonaws.mobileconnectors.s3.transferutility.UploadTask.call(UploadTask.java:93)
at com.amazonaws.mobileconnectors.s3.transferutility.UploadTask.call(UploadTask.java:49)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Why am i getting this error? (please help i cant find any solution to this online)
