Ошибка permission denied connect

I am receiving the following error when gradle checks maven for dependencies:

Error transferring file: Permission denied: connect

I have found that the issue may be related to a known bug in JDK 1.7 related to IPv6. The workaround, is to set -Djava.net.preferIPv4Stack=true in the Java VM options.

I have done this, and still receive the same error. I have tried setting every possible environment parameter I can think of, including MAVEN_OPTS, GRADLE_OPTS, _JPI_VM_OPTIONS, JAVA_OPTS, etc. Nothing appears to work. Could I be overlooking something simple here?

asked Nov 14, 2012 at 3:09

user1822604's user avatar

1

I have tried using -Djava.net.preferIPv4Stack=true when using gradle from the command line (with Minecraft Forge). When it fetches the dependencies and other files, it would throw a permission denied: connect error.

My solution to this problem is to look for a configuration file (.ini) and add -Djava.net.preferIPv4Stack=true, or I use it as an argument in the CLI, in this case:

gradlew cleancache --refresh-dependencies -Djava.net.preferIPv4Stack=true setupDecompWorkspace eclipse.

It works for me.

answered Sep 2, 2014 at 19:41

Eric Smith's user avatar

0

That sounds more like missing credentials against the given repository. In Maven you have to set those informations in the settings.xml file.

You need to authenticate against the given repository.

repositories {
    maven {
        credentials {
            username 'user'
            password 'password'
        }
        url "http://repo.mycompany.com/maven2"
    }
}

answered Nov 14, 2012 at 8:16

khmarbaise's user avatar

khmarbaisekhmarbaise

92.2k28 gold badges187 silver badges234 bronze badges

1

in Windows open -> Network and Sharing Center by searching it in windows start -> search

It will list the LAN connection and VPN

Go to the VPN

click on the connection.

click on properties button
un select ipv6 to disable

answered Jun 28, 2016 at 11:31

rinjan's user avatar

rinjanrinjan

5505 silver badges19 bronze badges

I am receiving the following error when gradle checks maven for dependencies:

Error transferring file: Permission denied: connect

I have found that the issue may be related to a known bug in JDK 1.7 related to IPv6. The workaround, is to set -Djava.net.preferIPv4Stack=true in the Java VM options.

I have done this, and still receive the same error. I have tried setting every possible environment parameter I can think of, including MAVEN_OPTS, GRADLE_OPTS, _JPI_VM_OPTIONS, JAVA_OPTS, etc. Nothing appears to work. Could I be overlooking something simple here?

asked Nov 14, 2012 at 3:09

user1822604's user avatar

1

I have tried using -Djava.net.preferIPv4Stack=true when using gradle from the command line (with Minecraft Forge). When it fetches the dependencies and other files, it would throw a permission denied: connect error.

My solution to this problem is to look for a configuration file (.ini) and add -Djava.net.preferIPv4Stack=true, or I use it as an argument in the CLI, in this case:

gradlew cleancache --refresh-dependencies -Djava.net.preferIPv4Stack=true setupDecompWorkspace eclipse.

It works for me.

answered Sep 2, 2014 at 19:41

Eric Smith's user avatar

0

That sounds more like missing credentials against the given repository. In Maven you have to set those informations in the settings.xml file.

You need to authenticate against the given repository.

repositories {
    maven {
        credentials {
            username 'user'
            password 'password'
        }
        url "http://repo.mycompany.com/maven2"
    }
}

answered Nov 14, 2012 at 8:16

khmarbaise's user avatar

khmarbaisekhmarbaise

92.2k28 gold badges187 silver badges234 bronze badges

1

in Windows open -> Network and Sharing Center by searching it in windows start -> search

It will list the LAN connection and VPN

Go to the VPN

click on the connection.

click on properties button
un select ipv6 to disable

answered Jun 28, 2016 at 11:31

rinjan's user avatar

rinjanrinjan

5505 silver badges19 bronze badges

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.

EDIT2:

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

99 / 81 / 93

Регистрация: 03.12.2013

Сообщений: 217

1

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


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

Java
1
java.net.preferIPv4Stack=true

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

Java
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(); }
            }
        }
}

Сервер:

Java
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();
            }
        }
    }
}

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

0

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

Fix the Java.Net.SocketException: Permission Denied 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.

Here are the main reasons for the error java.net.SocketException: Permission denied:

  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.

The possible solution for this can be:

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

  2. 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
    
  3. 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.

Недавно мы установили Docker в Ubuntu. Это было супер легко. Но когда мы попытались запустить команду docker, она выдала нам эту ошибку:

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.39/containers/json: dial unix /var/run/docker.sock: connect: permission denied

Дело не в том, что мы пытались запустить что-то особенное. Это происходит и для базовой команды docker, такой как ps.

Странно, не правда ли? Позвольте нам показать вам, как обойти эту досадную ошибку.

Исправление ошибки ‘Got permission denied while trying to connect to the Docker daemon socket’ в Docker в Ubuntu

Есть два способа справиться с этим.

Исправление 1: запустить все команды Docker с помощью sudo

Если у вас есть доступ к sudo в вашей системе, вы можете запустить каждую команду docker с помощью sudo, и вы больше не увидите ошибку ‘Got permission denied while trying to connect to the Docker daemon socket’.

sudo docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                    PORTS               NAMES
13dc0f4226dc        ubuntu              "bash"              17 hours ago        Exited (0) 16 hours ago                       container-2
2d9a8c190e6c        ubuntu              "/bin/bash"         17 hours ago        Created                                       container-1

Но запускать каждый раз команду docker с помощью sudo очень неудобно. Вы пропустите добавление sudo в начало, и вы снова получите сообщение об ошибке ‘permission denied’.

Исправление 2: Запуск команд docker без sudo

Чтобы запустить команды docker без sudo, вы можете добавить свою учетную запись пользователя (или учетную запись, для которой вы пытаетесь решить эту проблему) в группу docker.

Сначала создайте группу Docker. Группа может уже существовать, но выполнение команды создания группы не повредит.

sudo groupadd docker

Теперь, когда у вас есть группа Docker, добавьте своего пользователя в эту группу. Мы предполагаем, что вы пытаетесь сделать это для своей учетной записи, и в этом случае вы можете использовать переменную $USER.

sudo usermod -aG docker $USER

Убедитесь, что ваш пользователь был добавлен в группу Docker, перечислив пользователей группы. Вы, вероятно, должны выйти и снова войти в систему.

andreyex@destroyer:~$ groups
andreyex adm cdrom sudo dip plugdev lpadmin sambashare docker

Если вы проверите свои группы. а группы docker нет в списке даже после выхода из системы, возможно, вам придется перезапустить Ubuntu.

Теперь, если вы попытаетесь запустить команды docker без sudo, все должно работать нормально.

Дальнейшее устранение неисправностей

В некоторых случаях вам может потребоваться добавить дополнительные разрешения для некоторых файлов, особенно если вы в прошлом запускали команды docker с помощью sudo.

Вы можете попробовать изменить владельца группы для файла /var/run/docker.sock.

sudo chown root:docker /var/run/docker.sock

Вы также можете попробовать изменить владельца группы в каталоге ~/.docker.

sudo chown "$USER":"$USER" /home/"$USER"/.docker -R
sudo chmod g+rwx "$HOME/.docker" -R

А затем попробуйте запустить Docker с помощью sudo. Это должно быть хорошо.

Мы надеемся, что эта небольшая статья помогла вам исправить надоедливое:

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.39/containers/json: dial unix /var/run/docker.sock: connect: permission denied

с Docker в Ubuntu.

Это решило проблему для вас? Если да, мы приветствуем быстрый комментарий от вас.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Symptoms

Mail server configuration fails with the following exception in atlassian-fisheye-YYYY-MM-DD.log:

2014-12-02 10:44:29,856 ERROR [qtp1922315985-55427 -email-1417535069856] fisheye.mail Mailer-sendMessage - problem sending email
javax.mail.MessagingException: Could not connect to SMTP host: smtp.company.com, port: 25;
  nested exception is:
	java.net.SocketException: Permission denied: connect
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
	...
Caused by: java.net.SocketException: Permission denied: connect
	at java.net.TwoStacksPlainSocketImpl.socketConnect(Native Method)
	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
	at java.net.Socket.connect(Socket.java:579)
	at java.net.Socket.connect(Socket.java:528)
	at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
	at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
	at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
	... 161 more

Cause

  1. This is a known bug in Java 7, as per this post.
  2. This can be caused by anti-virus or firewall software blocking Java from connecting to the SMTP port.

Resolution

  1. Add -Djava.net.preferIPv4Stack=true to the FISHEYE_OPTS environment variable to help enable support for IPv4 on Java 7.
  2. Change the anti-virus or firewall software so that Java can connect to the SMTP server on the specified port.

Last modified on Nov 2, 2018

Related content

  • No related content found

I recently encountered a problem that is giving me a headache and I need help …

The System consists of two subsystems, called A and B, each running on a standalone Tomcat instance and currently running on the same machine. A invokes B’s service via Spring httpInvoker (i.e. over HTTP). B system also invokes the other system’s services via HTTP.

Symptoms:

  1. the system starts to run and appears to work normally for around 10-15 days;

  2. the system will run for a period of time after an exception:

    org.springframework.remoting.RemoteAccessException: Could not access HTTP invoker remote service at [http://xxx.xxx.xxx.xxx/remoting/call]; 
    

    The nested exception is

    java. net.SocketException: **Permission denied: connect**
    
  3. when the exception occurs, the system continues. This happens always, not only occasionally. (It looks like some resources are exhausted, but CPU rate < 5%, memory < 15%, network < 5%).

  4. when the system call between A and B fails, the B system call over HTTP to an external service also failed, with the same exception.

  5. Restarting both Tomcat services makes the whole system work properly.

So repeatedly following steps 1 — 5, I have not found the root reason.

Environment:

  • windows 2008 R2
  • tomcat7.0.42 x86_64
  • oralce-jdk-1.7.0_40

Any ideas?

asked May 28, 2014 at 1:53

luxinxian's user avatar

7

I had the same problem with RestTemplate. I changed the initialization to use HttpClient and it fixed my problem.

Here is the spring declaration I used :

<code>
    <bean id="httpClient" class="org.apache.http.impl.client.DefaultHttpClient">
        <constructor-arg>
            <bean class="org.apache.http.impl.conn.PoolingClientConnectionManager"/>
        </constructor-arg>
    </bean>

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate" >
        <constructor-arg>
            <bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
                <constructor-arg ref="httpClient"/>
            </bean>
        </constructor-arg>
    </bean>
</code>

This completely solved the problem (before, after a number of http requests (about 14500) I had the error about «connect».

Reaces's user avatar

Reaces

5,5774 gold badges36 silver badges46 bronze badges

answered Aug 19, 2015 at 9:26

JNG's user avatar


Linux, Программное обеспечение

  • 09.05.2016
  • 6 167
  • 1
  • 21.06.2022
  • 4
  • 3
  • 1

Ошибка error connect to php5-fpm.sock failed (13: Permission denied)

  • Содержание статьи
    • Описание ошибки
    • Исправление ошибки
    • Комментарии к статье ( 1 шт )
    • Добавить комментарий

Не смотря на то, что «связка» nginx + PHP уже перестала быть какой-то диковинкой, во многих дистрибьютивах взаимодействие данных программ не налажено должным образом. Ниже — пример типичной ошибки после установки nginx и php-fpm.

Описание ошибки

Если при попытке зайти на вебсервер под управлением nginx браузер выдает код ошибки 502 (Bad gateway), а в логах пишется примерно следующее:

connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream

то скорее всего проблема кроется в файле настроек PHP.

Исправление ошибки

Для исправления ошибки нужно открыть /etc/php5/fpm/pool.d/www.conf, и в нем найти следующие строчки:

;listen.owner = www-data
;listen.group = www-data
;listen.mode = 0660

и убрать комментарии в виде точки с запятой (если они конечно же там есть). В итоге все должно выглядеть так:

listen.owner = www-data
listen.group = www-data
listen.mode = 0660

Сохраняем файл конфига, и все что теперь осталось нужно, это перезапустить службу php-fpm (ниже приведены различные примеры для различных версий)

Для PHP5:

/etc/init.d/php5-fpm restart
systemctl restart php5-fpm

Для PHP7:

systemctl restart php7.0-fpm

Если же проблема не решилась, то следует проверить под каким пользователем работает веб-сервер nginx. Для этого стоит открыть его конфиг, который расположен по адресу /etc/nginx/nginx.conf. Ищем параметр user, он может выглядеть примерно вот так:

user nginx;

Исходя из этого, можно понять, что веб-сервер работает под пользователем nginx, а php5-fpm — под пользователем www-data. Решением такой проблемы может выступить смена пользователя, под которым работает nginx. Для этого, меняем в конфиге /etc/php5/fpm/pool.d/www.conf www-data на nginx, и перезагружаем php5-fpm.

/etc/init.d/php5-fpm restart

Recently, I installed Docker on Ubuntu. It was super easy. But when I tried to run a docker command, it threw this error at me:

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.39/containers/json: dial unix /var/run/docker.sock: connect: permission denied

It’s not that I am trying to run something special. It happens for basic docker command like ps as well.

Strange, isn’t it? Let me show you how to get past this annoying error.

Fixing ‘Got permission denied while trying to connect to the Docker daemon socket’ error with Docker in Ubuntu

There are two ways to deal with it.

Fix 1: Run all the docker commands with sudo

If you have sudo access on your system, you may run each docker command with sudo and you won’t see this ‘Got permission denied while trying to connect to the Docker daemon socket’ anymore.

sudo docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                    PORTS               NAMES
13dc0f4226dc        ubuntu              "bash"              17 hours ago        Exited (0) 16 hours ago                       container-2
2d9a8c190e6c        ubuntu              "/bin/bash"         17 hours ago        Created                                       container-1

But running each and every docker command with sudo is super inconvenient. You miss adding sudo to the beginning and you’ll get ‘permission denied’ error again.

Fix 2: Running docker commands without sudo

To run the docker commands without sudo, you can add your user account (or the account you are trying to fix this problem for) to the docker group.

First, create the docker group using groupadd command. The group may already exist but running the group creation command won’t hurt.

sudo groupadd docker

Now that you have the docker group, add your user to this group with the usermod command. I am assuming that you are trying to do it for your own user account and in that case, you can use the $USER variable.

sudo usermod -aG docker $USER

Verify that your user has been added to docker group by listing the users of the group. You probably have to log out and log in back again.

[email protected]:~$ groups
abhishek adm cdrom sudo dip plugdev lpadmin sambashare docker

If you check your groups and docker groups is not listed even after logging out, you may have to restart Ubuntu. To avoid that, you can use the newgrp command liks this:

newgrp docker

Now if you try running the docker commands without sudo, it should work just fine.

Further troubleshooting

In some cases, you may need to add additional permissions to some files specially if you have run the docker commands with sudo in the past.

You may try changing the group ownership of the /var/run/docker.sock file.

sudo chown root:docker /var/run/docker.sock

You may also try changing the group ownership of the ~/.docker directory.

sudo chown "$USER":"$USER" /home/"$USER"/.docker -R
sudo chmod g+rwx "$HOME/.docker" -R

And then try running docker with sudo. It should be fine.

I hope this little tutorial helped you to fix the annoying “Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.39/containers/json: dial unix /var/run/docker.sock: connect: permission denied” error with Docker in Ubuntu.

Did it fix the problem for you? If yes, I welcome a quick comment of thanks from you. If not, I’ll be happy to help you fix this problem further.

Abhishek Prakash

Creator of Linux Handbook and It’s FOSS. An ardent Linux user & open source promoter. Huge fan of classic detective mysteries from Agatha Christie and Sherlock Holmes to Columbo & Ellery Queen.

Today, I worked on a service request that our customer got the following error message using Java code: 

Exception in thread «main» com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host servername.database.windows.net, port 1433 has failed. Error: «Permission denied: connect. Verify the connect
ion properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.»

or 

«Exception in thread «main» com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host nodename.tenantring.northeurope1-a.worker.database.windows.net (redirected from servername.database.windows.
net), port 11001 has failed. Error: «Permission denied: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.». at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:234)
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:285)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2462)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:668)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2695)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2362)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2213)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1276)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:861)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)»

I would like to share with you what was my lessons learned here.

The first thing is to isolate the problem running the suggested Java code to see the results:

package testconnectionms;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.lang.model.util.ElementScanner6;
import javax.sql.DataSource;

/**
 * Simple connection test.
 *
 */
public class SQLTest
{
	static {
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		} catch (Exception ex) {
			System.err.println("Unable to load JDBC driver");
			ex.printStackTrace();
			System.exit(1);
		}
	}

	public static void main(String[] args)
		throws SQLException
	{
		String username   = "username";
		String password   = "Password";
		String envname    = "env";
		String seconds   = "10";
		        
		System.out.println("Arguements are: username="+username+",password="+password+",envname="+envname+",seconds="+seconds);
		
		String url = String.format("jdbc:sqlserver://servername.database.windows.net:1433;database=dbname;sslProtocol=TLSv1.2", envname,envname);

		System.out.println("-- Connecting to " + url);
		
		long start = System.currentTimeMillis();
		Connection connection = DriverManager.getConnection(url, username, password);

		if (false) {
			
		}
		
		final long time1 = System.currentTimeMillis();
		long time2 = time1;
		long cnt = 0;
		Integer secInt = Integer.valueOf(seconds);

        PreparedStatement st = connection.prepareStatement("SELECT * from demo");
		st.setQueryTimeout(20);
		while (time1 + (secInt.intValue() * 1000) >= time2)
		{
			cnt++;
			
			
			ResultSet rs = st.executeQuery();
			rs.next();
			rs.close();
			
			
			time2 = System.currentTimeMillis();
		}
		st.close();
		
		Long statementsCount = Long.valueOf(cnt);
		Long statementsPerSecond = Long.valueOf(cnt / ((time2 - time1) / 1000));
		Double timePerStatement = Double.valueOf(1000.0 / (cnt / ((time2 - time1) / 1000.0)));
		
		System.out.println("statementsCount="+statementsCount);
		System.out.println("statementsPerSecond="+statementsPerSecond);
		System.out.println("timePerStatement="+timePerStatement);
	}
	
	private static void usage(String msg)
	{
        System.err.println("Usage: SQLTest -username username -password password -envname envname -seconds seconds");
        System.err.println(msg);
	}
}

The error message: Permission denied: connect reports that when when trying to open the port any firewall/NSG is blocking this outbound port, either, 1433 or redirect port 11000-12000.

If the issue is regarding with port 1433 means that the initial connection with port 1433 is rejecting, if the error message any port from 11000-12000 means that the issue is rejecting any of this port.

As a workaround, if your customer only has the port 1433 as outbound open, please, change the connection policy to Proxy meanwhile their networking team is opening as outbound connection from 11000-12000.

For reference: Azure SQL Database connectivity architecture — Azure SQL Database and Azure Synapse Analytics | Micr…

Enjoy!

Студворк — интернет-сервис помощи студентам

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

Java
1
java.net.preferIPv4Stack=true

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

Java
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(); }
            }
        }
}

Сервер:

Java
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();
            }
        }
    }
}

  • Ошибка permission denied android
  • Ошибка pdf preview handler windows 10
  • Ошибка performance warning бесконечное лето
  • Ошибка pdc failure bmw e60
  • Ошибка performance warning rust