Java net socketexception android permission denied

Ошибка permission denied connect

I was wondering in what other circumstances this (SocketException: Permission denied: connect) error would be thrown from the line SocketAddress socketAddress = new InetSocketAddress(«86.143.5.16.

I was wondering in what other circumstances this (SocketException: Permission denied: connect) error would be thrown from the line

SocketAddress socketAddress = new InetSocketAddress("86.143.5.165", 6464); // Set a 3s timeout clientSocket.connect(socketAddress, 3000); 

There are a few Android issues relating to permissions, and when using a port < 1024.
I am running a simple java client/server app, on port 6464, and i am using java 1.6.0_32 (after reading that Java 1.7.0_7 adds ipv6 support).

I have port 80 forwarded to my server (verified on the client machine by going to my external IP in a browser), and the port 6464 is open also.

Why would the client be refused connection?

EDIT: I did originally get this error when trying to connect to the server from the server itself. (Obviously, I guess it’s like a telephone in that you get an engaged tone). I had a friend test it, and he could connect. I’m now connecting from a laptop that isn’t on the LAN (i.e. using a 3g mobile as a hotspot), but strangely still getting the error.

java.net.SocketException: Permission denied: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at runtime.MyGame.main(MyGame.java:31) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.sun.javaws.Launcher.executeApplication(Unknown Source) at com.sun.javaws.Launcher.executeMainClass(Unknown Source) at com.sun.javaws.Launcher.doLaunchApp(Unknown Source) at com.sun.javaws.Launcher.run(Unknown Source) at java.lang.Thread.run(Unknown Source) #### Java Web Start Error: #### Socket failed to connect 

24.07.2018, 21:41. Показов 1554. Ответов 0

В общем то, проблема следующая: изучаю Java, работал немного с ней до этого, но теперь более фундаментально взялся за нее. И вот проходил в книжке часть с созданием клиент-серверного приложения, и столкнулся с ошибкой Permission denied: connect при создание соединения клиентом. И застрял на этом. В Google, как не странно, довольно не много информации.
Использую Java 8. Писали что в Java 7 был баг, надо добавить строку

java.net.preferIPv4Stack=true

Но не помогло. Java обновлял буквально неделю назад. Тестировал и в Intelij, и в Eclipse, и через консоль.
Читал что может быть закрыт порт — отключил брандмауер виндовс, открыл порт в роутере. Порт точно открыт(проверил через консоль и программой). Тестирую все на компьютере своем. И из-за этой проблемы застрял.
Что еще странно — где-то года два назад, работал на этом же компьютере, писал сервер на Java, клиент на Андроид, и такая связка работала.
И не знаю что же делать? Пока две идеи: одна — удалить Java и поставить еще раз. Есть так же вариант снести эту версию(8) и попробовать Java 10 поставить.
Что кто может подсказать по этому поводу? Буду благодарен любым подсказкам.
В конце приведу коды клиента и сервера. Но оговорюсь, что проверял уже и с десяток других с интернета.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.*; public class SimpleChatClient  JTextArea incoming; JTextField outgoing; BufferedReader reader; PrintWriter writer; Socket sock; public static void main(String[] args) SimpleChatClient client = new SimpleChatClient(); client.go(); > public void go() JFrame frame = new JFrame("Java chat client"); JPanel mainPanel = new JPanel(); incoming = new JTextArea(15, 50); incoming.setLineWrap(true); incoming.setWrapStyleWord(true); incoming.setEditable(false); JScrollPane qScroller = new JScrollPane(incoming); qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); outgoing = new JTextField(20); JButton sendButton = new JButton("Send"); sendButton.addActionListener(new SendButtonListener()); mainPanel.add(qScroller); mainPanel.add(outgoing); mainPanel.add(sendButton); setUpNetworking(); Thread readerThread = new Thread(new IncomingReader()); readerThread.start(); frame.getContentPane().add(BorderLayout.CENTER, mainPanel); frame.setSize(400, 500); frame.setVisible(true); > private void setUpNetworking() System.setProperty("java.net.preferIPv4Stack" , "true"); try sock = new Socket("127.0.0.1", 4242); InputStreamReader streamReader = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(streamReader); writer = new PrintWriter(sock.getOutputStream()); System.out.println("networking established"); > catch(IOException ex)  ex.printStackTrace(); > > public class SendButtonListener implements ActionListener @Override public void actionPerformed(ActionEvent e)  try writer.println(outgoing.getText()); writer.flush(); > catch(Exception ex)  ex.printStackTrace(); > outgoing.setText(""); outgoing.requestFocus(); > > public class IncomingReader implements Runnable public void run() String message; try while ((message = reader.readLine()) != null) System.out.println("read " + message); incoming.append(message + "n"); > > catch(Exception ex)  ex.printStackTrace(); > > > >
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
import java.io.*; import java.net.*; import java.util.*; public class VerySimpleChatServer  ArrayList clientOutputStreams; public class ClientHandler implements Runnable  BufferedReader reader; Socket sock; public ClientHandler(Socket clientSocket)  try  // Open communication with client during init sock = clientSocket; InputStreamReader isReader = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(isReader); > catch (Exception ex) ex.printStackTrace();> > public void run()  String message; try  while ((message = reader.readLine()) != null)  System.out.println("read " + message); tellEveryone(message); > > catch (Exception ex)  ex.printStackTrace(); > > > // Close inner class. public static void main(String[] args)  new VerySimpleChatServer().go(); > public void go()  clientOutputStreams = new ArrayList(); try  // Bind to port 5000 System.out.println("Server ready on port 5000"); ServerSocket serverSock = new ServerSocket(4242); while (true)  // Bind Socket clientSocket = serverSock.accept(); // Build write channels to client PrintWriter writer = new PrintWriter(clientSocket.getOutputStream()); clientOutputStreams.add(writer); Thread t = new Thread(new ClientHandler(clientSocket)); t.start(); System.out.println("Got a connection!"); > > catch (Exception ex)  ex.printStackTrace(); > > public void tellEveryone(String message)  System.out.println("tellEveryone"); Iterator it = clientOutputStreams.iterator(); // Process queues with active items while (it.hasNext())  try  PrintWriter writer = (PrintWriter) it.next(); writer.println(message); writer.flush(); > catch (Exception ex)  ex.printStackTrace(); > > > >

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

Источник

Fix the Java.Net.SocketException: Permission Denied in Java

Fix the Java.Net.SocketException: Permission Denied in Java

  1. Causes of the java.net.SocketException: Permission denied Error in Java
  2. Fix the java.net.SocketException: Permission denied Error in Java

This tutorial demonstrates the java.net.SocketException: Permission denied error in Java.

Causes of the java.net.SocketException: Permission denied Error in Java

The SocketException usually occurs when there is a problem with the network connection. It can be Permission denied , Connection reset , or anything else.

The java.net.SocketException: Permission denied error occurs when there is no permission from the network to connect with a certain port. The error can occur while connecting or configuring the network settings on different platforms.

The error java.net.SocketException: Permission denied can occur on any server type like Tomcat or OpenShift.

  1. When the operating system doesn’t allow a particular port number.
  2. The antivirus or firewall stops the connection to a certain network.
  3. Sometimes a problem with the older version of Java.

Fix the java.net.SocketException: Permission denied Error in Java

For example, while configuring the HTTPS certificate for the Tomcat server, the error java.net.SocketException: Permission denied can occur while starting the server:

Caused by: java.net.SocketException: Permission denied  at sun.nio.ch.Net.bind0(Native Method)  at sun.nio.ch.Net.bind(Net.java:438)  at sun.nio.ch.Net.bind(Net.java:430)  at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:225)  at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)  at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:221)  at org.apache.tomcat.util.net.AbstractEndpoint.init(AbstractEndpoint.java:1118)  at org.apache.tomcat.util.net.AbstractJsseEndpoint.init(AbstractJsseEndpoint.java:223)  at org.apache.coyote.AbstractProtocol.init(AbstractProtocol.java:587)  at org.apache.coyote.http11.AbstractHttp11Protocol.init(AbstractHttp11Protocol.java:74)  at org.apache.catalina.connector.Connector.initInternal(Connector.java:1058)  . 13 more 

The reason for this error is that the operating system is stopping the connection. Because the Linux system doesn’t allow non-root users to use the root less than 1024; hence, it becomes a permission problem.

Now, the solutions to this problem can be:

  1. The best solution is to use the root account to start the Tomcat server.
  2. If Linux is not allowing port numbers less than 1024, use a port greater than this number. The port number will be added to the URL request.

Similarly, while using the openshift server, the same error java.net.SocketException: Permission denied can occur. And the reason could be either the firewall or antivirus is stopping it or the Java version you are using is not compatible.

Stop the antivirus and firewall. Or check they are not blocking the server.

Use Java 8 or above versions. Or put the following VM arguments in your application to be able to run and connect using Java 7:

-Djava.net.preferIPv4Stack=true 

Please check the third-party libraries or packages if they have some specific requirements. Some of them will also cause the java.net.SocketException: Permission denied error.

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

Related Article — Java Error

Источник

Читайте также:  Python all function example
Оцените статью