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 | ||
|
Но не помогло. Java обновлял буквально неделю назад. Тестировал и в Intelij, и в Eclipse, и через консоль.
Читал что может быть закрыт порт — отключил брандмауер виндовс, открыл порт в роутере. Порт точно открыт(проверил через консоль и программой). Тестирую все на компьютере своем. И из-за этой проблемы застрял.
Что еще странно — где-то года два назад, работал на этом же компьютере, писал сервер на Java, клиент на Андроид, и такая связка работала.
И не знаю что же делать? Пока две идеи: одна — удалить Java и поставить еще раз. Есть так же вариант снести эту версию(8) и попробовать Java 10 поставить.
Что кто может подсказать по этому поводу? Буду благодарен любым подсказкам.
В конце приведу коды клиента и сервера. Но оговорюсь, что проверял уже и с десяток других с интернета.
| Java | ||
|
Сервер:
| Java | ||
|
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
- Causes of the
java.net.SocketException: Permission deniedError in Java - Fix the
java.net.SocketException: Permission deniedError 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:
- When the operating system doesn’t allow a particular port number.
- The antivirus or firewall stops the connection to a certain network.
- 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:
- The best solution is to use the root account to start the Tomcat server.
- 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:
-
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 deniederror.
Недавно мы установили 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
- This is a known bug in Java 7, as per this post.
- This can be caused by anti-virus or firewall software blocking Java from connecting to the SMTP port.
Resolution
- Add
-Djava.net.preferIPv4Stack=trueto theFISHEYE_OPTSenvironment variable to help enable support for IPv4 on Java 7. - 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:
-
the system starts to run and appears to work normally for around 10-15 days;
-
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** -
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%).
-
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.
-
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
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
5,5774 gold badges36 silver badges46 bronze badges
answered Aug 19, 2015 at 9:26
Linux, Программное обеспечение
- 09.05.2016
- 6 167
- 1
- 21.06.2022
- 4
- 3
- 1

- Содержание статьи
- Описание ошибки
- Исправление ошибки
- Комментарии к статье ( 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.
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.