Error during system call connection reset by peer что означает

javax.net.ssl.SSLException: Read error: ssl=0x8ad9c2c0: I/O error during system call, Connection reset by peer #3594 Comments I try to make a http post request. Okhttp throws an sslexception. So I add some codes to trust all certificates. ResponseBody body = response.body(); int statusCode = response.code(); byte[] bodyBytes = body.bytes(); // **The exception occurs on this […]

Содержание

  1. javax.net.ssl.SSLException: Read error: ssl=0x8ad9c2c0: I/O error during system call, Connection reset by peer #3594
  2. Comments
  3. javax.net.ssl.SSLException: ошибка чтения: ssl = 0x9524b800: ошибка ввода-вывода во время системного вызова, сброс соединения одноранговым узлом

javax.net.ssl.SSLException: Read error: ssl=0x8ad9c2c0: I/O error during system call, Connection reset by peer #3594

I try to make a http post request. Okhttp throws an sslexception. So I add some codes to trust all certificates.

ResponseBody body = response.body(); int statusCode = response.code(); byte[] bodyBytes = body.bytes(); // **The exception occurs on this line**

Okhttp version is here

Trace is here:
javax.net.ssl.SSLException: Read error: ssl=0x8797a780: I/O error during system call, Connection reset by peer 09-11 11:56:44.811 25238-29849/ D/OkHttp: at com.android.org.conscrypt.NativeCrypto.SSL_read(Native Method) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:758) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at okio.Okio$2.read(Okio.java:139) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at okio.AsyncTimeout$2.read(AsyncTimeout.java:237) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at okio.RealBufferedSource.read(RealBufferedSource.java:46) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at okhttp3.internal.http1.Http1Codec$FixedLengthSource.read(Http1Codec.java:384) 09-11 11:56:44.812 25238-29849/ D/OkHttp: at okio.Buffer.writeAll(Buffer.java:1005) 09-11 11:56:44.812 25238-29849/ D/OkHttp: at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:107) 09-11 11:56:44.812 25238-29849/ D/OkHttp: at okhttp3.ResponseBody.bytes(ResponseBody.java:136)

I think this is not a server side problem. I just tried, volley works for same request.

The text was updated successfully, but these errors were encountered:

Источник

javax.net.ssl.SSLException: ошибка чтения: ssl = 0x9524b800: ошибка ввода-вывода во время системного вызова, сброс соединения одноранговым узлом

Наши клиенты начинают видеть сотни таких сообщений «Ошибка SSLException — сброс соединения одноранговым узлом» за последние пару недель, и я не могу понять, почему

Мы используем Retrofit с okhttp, без специальной конфигурации

Вышеупомянутый клиентский провайдер является одноэлементным. RestAdapter построен с использованием этого внедренного клиента (мы используем кинжал) —

Основываясь на решениях по переполнению стека, что я обнаружил —

Продолжительность сохранения активности на сервере составляет 180 секунд, OkHttp по умолчанию — 300 секунд.

Сервер возвращает «Connection: close» в своем заголовке, но запрос клиента отправляет «Connection: keepAlive».

Сервер поддерживает TLS 1.0 / 1.1 / 1.2 и использует Open SSL.

Наши серверы недавно переехали к другому хостинг-провайдеру в другой географии, поэтому я не знаю, сбои это DNS или нет.

Мы пробовали настроить такие вещи, как keepAlive, перенастроили OpenSSL на сервере, но по какой-то причине клиент Android продолжает получать эту ошибку

Это происходит немедленно, без каких-либо задержек, когда вы пытаетесь использовать приложение для публикации чего-либо или подтягивания для обновления (оно даже не выходит в сеть и не имеет задержки до того, как произойдет это исключение, что означает, что соединение уже разорвано). Но попытка сделать это несколько раз как-то «исправляет», и мы добиваемся успеха. Это случится снова позже

Мы сделали недействительными наши записи DNS на сервере, чтобы узнать, чем это вызвано, но это не помогло.

В основном это происходит в LTE, но я видел это и в Wi-Fi.

Я не хочу отключать поддержку активности, потому что большинство современных клиентов этого не делают. Кроме того, мы используем OkHttp 2.4, и это проблема для устройств, использующих сэндвич с мороженым, поэтому я надеюсь, что он позаботится об этих основных сетевых проблемах. Клиент iOS также получает эти исключения, но почти в 100 раз меньше (клиент iOS использует AFNetworking 2.0). Я изо всех сил пытаюсь найти что-то новое, чтобы попробовать на данный момент, любая помощь / идеи?

Обновление — добавление полной трассировки стека через okhttp

Недавно я столкнулся с проблемой при работе над некоторым устаревшим кодом. После поиска в Google я обнаружил, что проблема везде, но без какого-либо конкретного решения. Я работал над различными частями сообщения об исключении и проанализировал их ниже.

Анализ:

  1. SSLException : исключение произошло с SSL (Secure Socket Layer), который реализован в javax.net.ssl пакете JDK ( openJDK/oracleJDK/AndroidSDK )
  2. Read error ssl=# I/O error during system call : Ошибка при чтении из защищенного сокета. Произошло это при использовании нативных системных библиотек / драйвера. Обратите внимание, что все платформы solaris, Windows и т. Д. Имеют свои собственные библиотеки сокетов, которые используются SSL. Windows использует библиотеку WINSOCK.
  3. Connection reset by peer : Системная библиотека сообщает ECONNRESET об этом сообщении (отчеты Solaris, отчеты Windows WSAECONNRESET ), что сокет, используемый для передачи данных, больше не может использоваться, поскольку существующее соединение было принудительно закрыто удаленным хостом. Необходимо создать новый безопасный путь между хостом и клиентом.

Причина:

Понимая проблему, я пытаюсь найти причину сброса соединения и назвал следующие причины:

  • Одноранговое приложение на удаленном узле внезапно останавливается, узел перезагружается, узел или удаленный сетевой интерфейс отключен или удаленный узел использует жесткое закрытие.
  • Эта ошибка также может возникнуть, если соединение было прервано из-за активности проверки активности, обнаружившей сбой во время выполнения одной или нескольких операций. Выполняемые операции завершаются сбоем, а последующие операции завершаются сбоем . Network dropped connection on reset(On Windows(WSAENETRESET))Connection reset by peer(On Windows(WSAECONNRESET))
  • Если целевой сервер защищен брандмауэром, что верно в большинстве случаев, время жизни (TTL) или тайм-аут, связанный с портом, принудительно закрывает незанятое соединение по истечении заданного тайм-аута. это наш интерес

Разрешение:

  1. События на стороне сервера, такие как внезапная остановка службы, перезагрузка, отключение сетевого интерфейса, не могут быть обработаны никакими средствами.
  2. На стороне сервера настройте брандмауэр для данного порта с более высокими значениями времени жизни (TTL) или тайм-аута, например 3600 секунд.
  3. Клиенты могут «попробовать» поддерживать сеть в активном состоянии, чтобы избежать или уменьшить количество файлов Connection reset by peer .
  4. Обычно текущий сетевой трафик поддерживает соединение, и проблема / исключение возникает нечасто. У сильного Wi-Fi меньше всего шансов Connection reset by peer .
  5. В мобильных сетях 2G, 3G и 4G, где доставка пакетных данных является прерывистой и зависит от доступности мобильной сети, он может не сбрасывать таймер TTL на стороне сервера и приводить к ошибке Connection reset by peer .

Вот условия, которые предлагается установить на различных форумах для решения проблемы.

  • ConnectionTimeout: Используется только во время установления соединения. Если хосту требуется время для подключения, более высокое значение этого параметра заставляет клиента ждать подключения.
  • SoTimeout : Тайм-аут сокета — указывает максимальное время, в течение которого получен пакет данных, чтобы считать соединение активным. Если в течение заданного времени данные не получены, соединение считается остановленным / разорванным.
  • Linger : До какого времени сокет не должен закрываться, когда данные поставлены в очередь на отправку и для сокета вызывается функция закрытия сокета.
  • TcpNoDelay : Вы хотите отключить буфер, в котором хранятся и накапливаются TCP-пакеты, и отправлять их при достижении порогового значения? Установка этого значения в true пропустит буферизацию TCP, так что каждый запрос будет отправлен немедленно. Замедление в сети может быть вызвано увеличением сетевого трафика из-за более частой и меньшей передачи пакетов.

Таким образом, ни один из вышеперечисленных параметров не помогает поддерживать сеть в рабочем состоянии и, следовательно, неэффективно.

Я нашел один параметр, который может помочь решить проблему, связанную с этими функциями.

Как я решил свою проблему?

  • Установить HttpConnectionParams.setSoKeepAlive(params, true)
  • Поймайте SSLException и проверьте сообщение об исключении для Connection reset by peer
  • Если обнаружено исключение, сохраните прогресс загрузки / чтения и создайте новое соединение.
  • Если возможно, возобновите загрузку / прочтите, иначе перезапустите загрузку

Надеюсь, подробности помогут. Удачного кодирования .

Источник

Connection Reset by peer means the remote side is terminating the session. This error is generated when the OS receives notification of TCP Reset (RST) from the remote peer.

Understanding Connection Reset by peer

Connection reset by peer means the TCP stream was abnormally closed from the other end. A TCP RST was received and the connection is now closed. This occurs when a packet is sent from our end of the connection but the other end does not recognize the connection; it will send back a packet with the RST bit set in order to forcibly close the connection.

“Connection reset by peer” is the TCP/IP equivalent of slamming the phone back on the hook. It’s more polite than merely not replying, leaving one hanging. But it’s not the FIN-ACK expected of the truly polite TCP/IP.

Understanding RST TCP Flag

RST is used to abort connections. It is very useful to troubleshoot a network connection problem.

RST (Reset the connection). Indicates that the connection is being aborted. For active connections, a node sends a TCP segment with the RST flag in response to a TCP segment received on the connection that is incorrect, causing the connection to fail.

The sending of an RST segment for an active connection forcibly terminates the connection, causing data stored in send and receive buffers or in transit to be lost. For TCP connections being established, a node sends an RST segment in response to a connection establishment request to deny the connection attempt. The sender will get Connection Reset by peer error.

Understanding TCP Flags SYN ACK RST FIN URG PSH

Check network connectivity 

The “ping” command is a tool used to test the availability of a network resource. The “ping” command sends a series of packets to a network resource and then measures the amount of time it takes for the packets to return.

If you want to ping a remote server, you can use the following command: ping <remote server>

In this example, “<remote server>” is the IP address or hostname of the remote server that you want to ping.

Ping the remote host we were connected to. If it doesn’t respond, it might be offline or there might be a network problem along the way. If it does respond, this problem might have been a transient one (so we can reconnect now)

If you are experiencing packet loss when pinging a remote server, there are a few things that you can do to troubleshoot the issue.

The first thing that you can do is check the network interface on the remote server. To do this, use the “ifconfig” command. The output of the “ifconfig” command will show you the status of all network interfaces on the system. If there is a problem with one of the interfaces, it will be shown in the output.

You can also use the “ip route” command to check routing information. The output of the “ip route” command will show you a list of all routes on the system. If there is a problem with one of the routes, it will be shown in the output.

If you are still experiencing packet loss, you can try to use a different network interface. To do this, use the “ping” command with the “-i” option. For example, the following command will use the eth0 interface:

ping -i eth0 google.com

Check remote service port is open

A port is a logical entity which acts as a endpoint of communication associated with an application or process on an Linux operating system. We can use some Linux commands to check remote port status.

Commands like nc, curl can be used to check if remote ports are open or not. For example, the following command will check if port 80 is open on google.com:

nc -zv google.com 80

The output of the above command should look something like this: Connection to google.com port 80 [tcp/80] succeeded!

This means that the port is open and we can establish a connection to it.

6 ways to Check a remote port is open in Linux

Check application log on remote server

For example, if the error is related with SSH. we can debug this on the remote server from sshd logs. The log entries will be in one of the files in the /var/log directory. SSHD will be logging something every time it drops our session.

Oct 22 12:09:10 server internal-sftp[4929]: session closed for local user fred from [192.0.2.33]

Check related Linux kernel parameters

Kernel parameter is also related to Connection Reset by peer error. The keepalive concept is very simple: when we set up a TCP connection, we associate a set of timers. Some of these timers deal with the keepalive procedure. When the keepalive timer reaches zero, we send our peer a keepalive probe packet with no data in it and the ACK flag turned on.

we can do this because of the TCP/IP specifications, as a sort of duplicate ACK, and the remote endpoint will have no arguments, as TCP is a stream-oriented protocol. On the other hand, we will receive a reply from the remote host (which doesn’t need to support keepalive at all, just TCP/IP), with no data and the ACK set.

If we receive a reply to we keepalive probe, we can assert that the connection is still up and running without worrying about the user-level implementation. In fact, TCP permits us to handle a stream, not packets, and so a zero-length data packet is not dangerous for the user program.

we usually use tcp keepalive for two tasks:

  • Checking for dead peers
  • Preventing disconnection due to network inactivity

Check Application heartbeat configuration

Connection Reset by peer error is also related to the application. Certain networking tools (HAproxy, AWS ELB) and equipment (hardware load balancers) may terminate “idle” TCP connections when there is no activity on them for a certain period of time. Most of the time it is not desirable.

We will use rabbitmq as an example. When heartbeats are enabled on a connection, it results in periodic light network traffic. Therefore heartbeats have a side effect of guarding client connections that can go idle for periods of time against premature closure by proxies and load balancers.

With a heartbeat timeout of 30 seconds the connection will produce periodic network traffic roughly every 15 seconds. Activity in the 5 to 15 second range is enough to satisfy the defaults of most popular proxies and load balancers. Also see the section on low timeouts and false positives above.

Check OS metric on peer side

Connection Reset by peer can be triggered by a busy system. we can setup a monitoring for our Linux system to the metrics like CPU, memory, network etc. If the system is too busy, the network will be impacted by this.

For example, we can use the “top” command to check the CPU usage. The output of the “top” command will show us the list of processes sorted by CPU usage. If there is a process which is using a lot of CPU, we can investigate this further to see if it is causing the network issues.

We can also use the “netstat” command to check network statistics. The output of the “netstat” command will show us a list of active network connections. If there are too many connections established, this could be causing the network issues.

We can use these commands to troubleshoot network issues on a Linux system. By using these commands, we can narrow down the root cause of the issue and fix it.

Monitoring Linux System with Telegraf Influxdb Grafana

Troubleshoot Network Slow Problems In Linux

Some time developers face issue this issue  in development mode there could anything that cause this issue

SocketException: OS Error: Connection reset by peer, errno = 104

Reason 

It may be your ISP blocking the connection

Flutter corrupted build package etc..

Solutions 1:

To solve this issue run the following commands

  • Step 1: flutter clean 
  • Step 2: flutter pub cache repair
  • Solutions 2:

    • Use different VPN
    • or Connect with your internet service provider to unblock respective URL

    Flutter Error: 

    some developer face this issue running in debug mode

    Write error: ssl=0x709bd56fc8: I/O error during system call, Connection reset by peer

    Solutions 1:

    To solve this issue run the following commands

  • Step 1: flutter clean 
  • For example:

    D:MobilemyApp>flutter clean
    Deleting build… 4,739ms (!)
    Deleting .dart_tool… 13ms
    Deleting Generated.xcconfig… 5ms
    Deleting flutter_export_environment.sh… 7ms 

    I try to make a http post request. Okhttp throws an sslexception. So I add some codes to trust all certificates.

    ResponseBody body = response.body(); int statusCode = response.code(); byte[] bodyBytes = body.bytes(); // **The exception occurs on this line**

    Trace is here:
    javax.net.ssl.SSLException: Read error: ssl=0x8797a780: I/O error during system call, Connection reset by peer 09-11 11:56:44.811 25238-29849/ D/OkHttp: at com.android.org.conscrypt.NativeCrypto.SSL_read(Native Method) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.read(OpenSSLSocketImpl.java:758) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at okio.Okio$2.read(Okio.java:139) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at okio.AsyncTimeout$2.read(AsyncTimeout.java:237) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at okio.RealBufferedSource.read(RealBufferedSource.java:46) 09-11 11:56:44.811 25238-29849/ D/OkHttp: at okhttp3.internal.http1.Http1Codec$FixedLengthSource.read(Http1Codec.java:384) 09-11 11:56:44.812 25238-29849/ D/OkHttp: at okio.Buffer.writeAll(Buffer.java:1005) 09-11 11:56:44.812 25238-29849/ D/OkHttp: at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:107) 09-11 11:56:44.812 25238-29849/ D/OkHttp: at okhttp3.ResponseBody.bytes(ResponseBody.java:136)

    X509TrustManager trustManager = new X509TrustManager() {
       @Override
       public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
       }
    
       @Override
       public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
       }
    
       @Override
       public java.security.cert.X509Certificate[] getAcceptedIssuers() {
           return new X509Certificate[]{};
       }
    };
    
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    sslSocketFactory = sslContext.getSocketFactory();
    clientBuilder.sslSocketFactory(sslSocketFactory, trustManager);
    
    clientBuilder.hostnameVerifier(new HostnameVerifier() {
       @Override
       public boolean verify(String hostname, SSLSession session) {
           return true;
       }
    });
    client = clientBuilder.build();
    client.retryOnConnectionFailure();
    

    I think this is not a server side problem. I just tried, volley works for same request.

    Понравилась статья? Поделить с друзьями:
  • Error during ssl handshake with remote server returned by
  • Error during sonarqube scanner execution
  • Error during simulation turbulence fd
  • Error during session construction перевести
  • Error during servletcontainerinitializer processing