Error connect ehostunreach

Hi, I have a project with restify that sends data to an api with axios. When I start both apis locally the axios shows this message { Error: connect EHOSTUNREACH 0.0.31.153:80 - Local (192.168.2.11...

Hi @carvalhoviniciusluiz , I encountered this problem today. By doing debug, I found some reason may cause this problem.

It’s about your system bash/zsh proxy settings

export https_proxy=localhost:8888
export http_proxy=localhost:8888

axios will automatically detect your default proxys and use them.

axios/lib/adapters/http.js

var proxy = config.proxy;
    if (!proxy) {
      var proxyEnv = protocol.slice(0, -1) + '_proxy';
      var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];
      if (proxyUrl) {
        var parsedProxyUrl = url.parse(proxyUrl);
        proxy = {
          host: parsedProxyUrl.hostname,
          port: parsedProxyUrl.port
        };

        if (parsedProxyUrl.auth) {
          var proxyUrlAuth = parsedProxyUrl.auth.split(':');
          proxy.auth = {
            username: proxyUrlAuth[0],
            password: proxyUrlAuth[1]
          };
        }
      }
    }

the result of url.parse('localhost:8888'):

image

get the wrong hostname

Then your dns will find this hostname, as a result, it returns 0.0.xx.xxx, which throw errors.

so just remove https_proxy and http_proxy and restart your terminal

I’m having an issue with nodemailer and would appreciate your help.

I am trying to send mail through nodemailer on node.js. EHOSTUNREACH error keeps popping up.I tried with two different services however, I keep getting the same error. My error log looks like

{ [Error: connect EHOSTUNREACH 65.55.163.152:587]
  code: 'EHOSTUNREACH',
  errno: 'EHOSTUNREACH',
  syscall: 'connect',
  address: '65.55.163.152',
  port: 587,
  stage: 'init' }

The code that I’m using in my application is:

var smtpTransport = nodemailer.createTransport("SMTP",{
service: "hotmail",
auth: {
user: "xyz@hotmail.com",
pass: "password"
}
}); 




api.post('/send',function(req,res){
    var mailOptions={
        from:'xyz@hotmail.com',
        to : req.body.to,
        subject : req.body.subject,
        text1 : req.body.text1
    }
    console.log(mailOptions);
    smtpTransport.sendMail(mailOptions, function(error, response){
        if(error){
            console.log(error);
            res.end("error");
        }
        else{
            console.log("Message sent: " + response.message);
            res.end("sent");
        }
    });
})  

I am fairly new to node and fail to understand the reason for this occurance. Any help on the matter is solicited.

You will encounter various kinds of errors while developing Node.js
applications, but most can be avoided or easily mitigated with the right coding
practices. However, most of the information to fix these problems are currently
scattered across various GitHub issues and forum posts which could lead to
spending more time than necessary when seeking solutions.

Therefore, we’ve compiled this list of 15 common Node.js errors along with one
or more strategies to follow to fix each one. While this is not a comprehensive
list of all the errors you can encounter when developing Node.js applications,
it should help you understand why some of these common errors occur and feasible
solutions to avoid future recurrence.

🔭 Want to centralize and monitor your Node.js error logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

1. ECONNRESET

ECONNRESET is a common exception that occurs when the TCP connection to
another server is closed abruptly, usually before a response is received. It can
be emitted when you attempt a request through a TCP connection that has already
been closed or when the connection is closed before a response is received
(perhaps in case of a timeout). This exception will usually
look like the following depending on your version of Node.js:

Output

Error: socket hang up
    at connResetException (node:internal/errors:691:14)
    at Socket.socketOnEnd (node:_http_client:466:23)
    at Socket.emit (node:events:532:35)
    at endReadableNT (node:internal/streams/readable:1346:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'ECONNRESET'
}

If this exception occurs when making a request to another server, you should
catch it and decide how to handle it. For example, you can retry the request
immediately, or queue it for later. You can also investigate your timeout
settings if you’d like to wait longer for the request to be
completed.

On the other hand, if it is caused by a client deliberately closing an
unfulfilled request to your server, then you don’t need to do anything except
end the connection (res.end()), and stop any operations performed in
generating a response. You can detect if a client socket was destroyed through
the following:

app.get("/", (req, res) => {
  // listen for the 'close' event on the request
  req.on("close", () => {
    console.log("closed connection");
  });

  console.log(res.socket.destroyed); // true if socket is closed
});

2. ENOTFOUND

The ENOTFOUND exception occurs in Node.js when a connection cannot be
established to some host due to a DNS error. This usually occurs due to an
incorrect host value, or when localhost is not mapped correctly to
127.0.0.1. It can also occur when a domain goes down or no longer exists.
Here’s an example of how the error often appears in the Node.js console:

Output

Error: getaddrinfo ENOTFOUND http://localhost
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'http://localhost'
}

If you get this error in your Node.js application or while running a script, you
can try the following strategies to fix it:

Check the domain name

First, ensure that you didn’t make a typo while entering the domain name. You
can also use a tool like DNS Checker to confirm that
the domain is resolving successfully in your location or region.

Check the host value

If you’re using http.request() or https.request() methods from the standard
library, ensure that the host value in the options object contains only the
domain name or IP address of the server. It shouldn’t contain the protocol,
port, or request path (use the protocol, port, and path properties for
those values respectively).

// don't do this
const options = {
  host: 'http://example.com/path/to/resource',
};

// do this instead
const options = {
  host: 'example.com',
  path: '/path/to/resource',
};

http.request(options, (res) => {});

Check your localhost mapping

If you’re trying to connect to localhost, and the ENOTFOUND error is thrown,
it may mean that the localhost is missing in your hosts file. On Linux and
macOS, ensure that your /etc/hosts file contains the following entry:

You may need to flush your DNS cache afterward:

sudo killall -HUP mDNSResponder # macOS

On Linux, clearing the DNS cache depends on the distribution and caching service
in use. Therefore, do investigate the appropriate command to run on your system.

3. ETIMEDOUT

The ETIMEDOUT error is thrown by the Node.js runtime when a connection or HTTP
request is not closed properly after some time. You might encounter this error
from time to time if you configured a timeout on your
outgoing HTTP requests. The general solution to this issue is to catch the error
and repeat the request, preferably using an
exponential backoff
strategy so that a waiting period is added between subsequent retries until the
request eventually succeeds, or the maximum amount of retries is reached. If you
encounter this error frequently, try to investigate your request timeout
settings and choose a more appropriate value for the endpoint
if possible.

4. ECONNREFUSED

The ECONNREFUSED error is produced when a request is made to an endpoint but a
connection could not be established because the specified address wasn’t
reachable. This is usually caused by an inactive target service. For example,
the error below resulted from attempting to connect to http://localhost:8000
when no program is listening at that endpoint.

Error: connect ECONNREFUSED 127.0.0.1:8000
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)
Emitted 'error' event on ClientRequest instance at:
    at Socket.socketErrorListener (node:_http_client:442:9)
    at Socket.emit (node:events:526:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8000
}

The fix for this problem is to ensure that the target service is active and
accepting connections at the specified endpoint.

5. ERRADDRINUSE

This error is commonly encountered when starting or restarting a web server. It
indicates that the server is attempting to listen for connections at a port that
is already occupied by some other application.

Error: listen EADDRINUSE: address already in use :::3001
    at Server.setupListenHandle [as _listen2] (node:net:1330:16)
    at listenInCluster (node:net:1378:12)
    at Server.listen (node:net:1465:7)
    at Function.listen (/home/ayo/dev/demo/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/ayo/dev/demo/main.js:16:18)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1357:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 3001
}

The easiest fix for this error would be to configure your application to listen
on a different port (preferably by updating an environmental variable). However,
if you need that specific port that is in use, you can find out the process ID
of the application using it through the command below:

Output

COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    2902  ayo   19u  IPv6 781904      0t0  TCP *:3001 (LISTEN)

Afterward, kill the process by passing the PID value to the kill command:

After running the command above, the application will be forcefully closed
freeing up the desired port for your intended use.

6. EADDRNOTAVAIL

This error is similar to EADDRINUSE because it results from trying to run a
Node.js server at a specific port. It usually indicates a configuration issue
with your IP address, such as when you try to bind your server to a static IP:

const express = require('express');
const app = express();

const server = app.listen(3000, '192.168.0.101', function () {
  console.log('server listening at port 3000......');
});

Output

Error: listen EADDRNOTAVAIL: address not available 192.168.0.101:3000
    at Server.setupListenHandle [as _listen2] (node:net:1313:21)
    at listenInCluster (node:net:1378:12)
    at doListen (node:net:1516:7)
    at processTicksAndRejections (node:internal/process/task_queues:84:21)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1357:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRNOTAVAIL',
  errno: -99,
  syscall: 'listen',
  address: '192.168.0.101',
  port: 3000
}

To resolve this issue, ensure that you have the right IP address (it may
sometimes change), or you can bind to any or all IPs by using 0.0.0.0 as shown
below:

var server = app.listen(3000, '0.0.0.0', function () {
  console.log('server listening at port 3000......');
});

7. ECONNABORTED

The ECONNABORTED exception is thrown when an active network connection is
aborted by the server before reading from the request body or writing to the
response body has completed. The example below demonstrates how this problem can
occur in a Node.js program:

const express = require('express');
const app = express();
const path = require('path');

app.get('/', function (req, res, next) {
  res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
    console.log(err);
  });
  res.end();
});

const server = app.listen(3000, () => {
  console.log('server listening at port 3001......');
});

Output

Error: Request aborted
    at onaborted (/home/ayo/dev/demo/node_modules/express/lib/response.js:1030:15)
    at Immediate._onImmediate (/home/ayo/dev/demo/node_modules/express/lib/response.js:1072:9)
    at processImmediate (node:internal/timers:466:21) {
  code: 'ECONNABORTED'
}

The problem here is that res.end() was called prematurely before
res.sendFile() has had a chance to complete due to the asynchronous nature of
the method. The solution here is to move res.end() into sendFile()‘s
callback function:

app.get('/', function (req, res, next) {
  res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
    console.log(err);
    res.end();
  });
});

8. EHOSTUNREACH

An EHOSTUNREACH exception indicates that a TCP connection failed because the
underlying protocol software found no route to the network or host. It can also
be triggered when traffic is blocked by a firewall or in response to information
received by intermediate gateways or switching nodes. If you encounter this
error, you may need to check your operating system’s routing tables or firewall
setup to fix the problem.

9. EAI_AGAIN

Node.js throws an EAI_AGAIN error when a temporary failure in domain name
resolution occurs. A DNS lookup timeout that usually indicates a problem with
your network connection or your proxy settings. You can get this error when
trying to install an npm package:

Output

npm ERR! code EAI_AGAIN
npm ERR! syscall getaddrinfo
npm ERR! errno EAI_AGAIN
npm ERR! request to https://registry.npmjs.org/nestjs failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org

If you’ve determined that your internet connection is working correctly, then
you should investigate your DNS resolver settings (/etc/resolv.conf) or your
/etc/hosts file to ensure it is set up correctly.

10. ENOENT

This error is a straightforward one. It means «Error No Entity» and is raised
when a specified path (file or directory) does not exist in the filesystem. It
is most commonly encountered when performing an operation with the fs module
or running a script that expects a specific directory structure.

fs.open('non-existent-file.txt', (err, fd) => {
  if (err) {
    console.log(err);
  }
});

Output

[Error: ENOENT: no such file or directory, open 'non-existent-file.txt'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'non-existent-file.txt'
}

To fix this error, you either need to create the expected directory structure or
change the path so that the script looks in the correct directory.

11. EISDIR

If you encounter this error, the operation that raised it expected a file
argument but was provided with a directory.

// config is actually a directory
fs.readFile('config', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Output

[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}

Fixing this error involves correcting the provided path so that it leads to a
file instead.

12. ENOTDIR

This error is the inverse of EISDIR. It means a file argument was supplied
where a directory was expected. To avoid this error, ensure that the provided
path leads to a directory and not a file.

fs.opendir('/etc/passwd', (err, _dir) => {
  if (err) throw err;
});

Output

[Error: ENOTDIR: not a directory, opendir '/etc/passwd'] {
  errno: -20,
  code: 'ENOTDIR',
  syscall: 'opendir',
  path: '/etc/passwd'
}

13. EACCES

The EACCES error is often encountered when trying to access a file in a way
that is forbidden by its access permissions. You may also encounter this error
when you’re trying to install a global NPM package (depending on how you
installed Node.js and npm), or when you try to run a server on a port lower
than 1024.

fs.readFile('/etc/sudoers', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Output

[Error: EACCES: permission denied, open '/etc/sudoers'] {
  errno: -13,
  code: 'EACCES',
  syscall: 'open',
  path: '/etc/sudoers'
}

Essentially, this error indicates that the user executing the script does not
have the required permission to access a resource. A quick fix is to prefix the
script execution command with sudo so that it is executed as root, but this is
a bad idea
for security reasons.

The correct fix for this error is to give the user executing the script the
required permissions to access the resource through the chown command on Linux
in the case of a file or directory.

sudo chown -R $(whoami) /path/to/directory

If you encounter an EACCES error when trying to listen on a port lower than
1024, you can use a higher port and set up port forwarding through iptables.
The following command forwards HTTP traffic going to port 80 to port 8080
(assuming your application is listening on port 8080):

sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

If you encounter EACCES errors when trying to install a global npm package,
it usually means that you installed the Node.js and npm versions found in your
system’s repositories. The recommended course of action is to uninstall those
versions and reinstall them through a Node environment manager like
NVM or Volta.

14. EEXIST

The EEXIST error is another filesystem error that is encountered whenever a
file or directory exists, but the attempted operation requires it not to exist.
For example, you will see this error when you attempt to create a directory that
already exists as shown below:

const fs = require('fs');

fs.mkdirSync('temp', (err) => {
  if (err) throw err;
});

Output

Error: EEXIST: file already exists, mkdir 'temp'
    at Object.mkdirSync (node:fs:1349:3)
    at Object.<anonymous> (/home/ayo/dev/demo/main.js:3:4)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  errno: -17,
  syscall: 'mkdir',
  code: 'EEXIST',
  path: 'temp'
}

The solution here is to check if the path exists through fs.existsSync()
before attempting to create it:

const fs = require('fs');

if (!fs.existsSync('temp')) {
  fs.mkdirSync('temp', (err) => {
    if (err) throw err;
  });
}

15. EPERM

The EPERM error may be encountered in various scenarios, usually when
installing an npm package. It indicates that the operation being carried out
could not be completed due to permission issues. This error often indicates that
a write was attempted to a file that is in a read-only state although you may
sometimes encounter an EACCES error instead.

Here are some possible fixes you can try if you run into this problem:

  1. Close all instances of your editor before rerunning the command (maybe some
    files were locked by the editor).
  2. Clean the npm cache with npm cache clean --force.
  3. Close or disable your Anti-virus software if have one.
  4. If you have a development server running, stop it before executing the
    installation command once again.
  5. Use the --force option as in npm install --force.
  6. Remove your node_modules folder with rm -rf node_modules and install them
    once again with npm install.

Conclusion

In this article, we covered 15 of the most common Node.js errors you are likely
to encounter when developing applications or utilizing Node.js-based tools, and
we discussed possible solutions to each one. This by no means an exhaustive list
so ensure to check out the
Node.js errors documentation or the
errno(3) man page for a
more comprehensive listing.

Thanks for reading, and happy coding!

Check Uptime, Ping, Ports, SSL and more.

Get Slack, SMS and phone incident alerts.

Easy on-call duty scheduling.

Create free status page on your domain.

Got an article suggestion?
Let us know

Share on Twitter

Share on Facebook

Share via e-mail

Next article

How to Configure Nginx as a Reverse Proxy for Node.js Applications

Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Содержание

  1. connect ehostunreach 0.0.31.153:80 #1514
  2. Comments
  3. carvalhoviniciusluiz commented May 1, 2018
  4. environment
  5. koresar commented May 17, 2018
  6. carvalhoviniciusluiz commented May 18, 2018
  7. koresar commented May 21, 2018
  8. mapleeit commented May 29, 2018 •
  9. Android TCP: ошибка EHOSTUNREACH
  10. Ошибка EHOSTUNREACH при отправке HTTP-запроса из приложения Hubot в приложение Rails локально
  11. Клиент TCPIP — EHOSTUNREACH (нет маршрута к хосту)
  12. 7 ответы
  13. Клиент TCPIP-EHOSTUNREACH (нет маршрута к хосту)
  14. 6 ответов

connect ehostunreach 0.0.31.153:80 #1514

Hi, I have a project with restify that sends data to an api with axios. When I start both apis locally the axios shows this message

I noticed that this post #1228 is similar to mine, but it’s closed.
How do you solve this?

environment

os: macOS
node: v8.9.3
npm: 5.5.1
axios: 0.18.0

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

IP addresses can’t start with 0. Thus the EHOSTUNREACH error. See here for example: https://superuser.com/questions/665502/why-cant-ip-addresses-start-with-0-or-255

This issue should be closed.

but the local ip does not begin with 0. As it is construction, the project is raised in the local address (localhost or 127.0.0.1)

this message is not making sense because of this

You’d need to find why the address is

Hi @carvalhoviniciusluiz , I encountered this problem today. By doing debug, I found some reason may cause this problem.

It’s about your system bash/zsh proxy settings

axios will automatically detect your default proxys and use them.

the result of url.parse(‘localhost:8888’) :

get the wrong hostname

Then your dns will find this hostname, as a result, it returns 0.0.xx.xxx, which throw errors.

so just remove https_proxy and http_proxy and restart your terminal

Источник

Android TCP: ошибка EHOSTUNREACH

Я использую TCP-соединение в своем приложении для Android. Соединение выполняется в выделенном потоке.

Затем я подключаю устройство android к Wi-Fi другого устройства, когда я запускаю приложение; он работает хорошо: я получаю передачу данных другим устройством.
Когда я остановлю соединение и начну снова (через несколько секунд), он будет работать.

Но когда я жду 2 или 3 минуты, соединение стало невозможным:

Я получаю следующее исключение:

Если я хочу снова использовать соединение, я должен обновить wifi-соединение (в параметрах Android, остановить и перезапустить Wi-Fi и подключиться к Wi-Fi устройства).

В чем может быть проблема? Есть ли проблема, когда я закрываю сокет после ошибки?

Ошибка EHOSTUNREACH означает, что адресат не отвечает.

В основном это может произойти несколькими способами:

  • Уровень передачи данных удалился (т.е. Wi-Fi упал)
  • Таблица маршрутизации изменилась, и пакеты больше не прибывают в желаемый пункт назначения
  • Брандмауэр отбрасывает пакеты.
  • Удаленный хост не отвечает на запрос соединения (порт, вероятно, закрыт, но отфильтрован)

Вы можете попробовать подключиться к другим портам в пункте назначения. Если это работает, когда ваше приложение этого не делает, приложение приема (сервера) перестает слушать. Если все порты, которые были доступны, внезапно отсутствуют, то это ваша таблица WiFi или маршрутизации или общая проблема брандмауэра.

У вас все еще есть допустимый IP-маршрут для этого хоста, но если он будет фильтровать запросы на подключение по соображениям безопасности, вы получите эту ошибку. Фильтрация распространена для закрытых портов, так что сканирование портов устройством не обнаруживает ничего, кроме пустого отверстия, как будто ничего не было по этому адресу. Я не мог найти окончательную ссылку, что Android делает это, но кажется вероятным.

Источник

Ошибка EHOSTUNREACH при отправке HTTP-запроса из приложения Hubot в приложение Rails локально

Я разрабатываю бота Slack (используя Хубот), а также приложение Rails, которое будет получать от него HTTP-запросы и обрабатывать их соответствующим образом. В основном, шаги высокого уровня того, что я хочу сделать, выглядят так:

  1. Неактивный пользователь отправляет боту триггерное слово (скажем, триггер «пока»).
  2. Hubot получает триггер, а затем отправляет запрос в приложение Rails.
  3. Приложение Rails помечает пользователя Slack как отсутствующего на рабочем месте.

Кажется, у меня есть какая-то проблема с маршрутизацией, потому что я получаю ошибку EHOSTUNREACH , когда пытаюсь выполнить этот поток с обоими загруженными приложениями ( rails s для Rails и ./bin/hubot —adapter slack для Hubot). Я предполагаю, что Hubot вообще не может получить доступ к приложению Rails. Я что-то упустил здесь? Какой URL-адрес мне нужно использовать, чтобы эти приложения могли отправлять запросы друг другу?

Я также пытался поменять местами 127.0.0.1:3000 на localhost:3000 , но результат остался прежним.

Код Хубота

Результаты журнала, когда я отправляю триггерное слово боту

Журнал сервера Rails (это определенно порт 3000)

Проверьте, что вы получаете в браузере с локальный: 3000, если это не работает, у вас, вероятно, проблемы с конфигурацией локальной сети. Если это сработает, попробуйте изменить код на robot.http(«http://localhost:3000») и обновите свой пост, указав результат. Ваше сообщение об ошибке, похоже, указывает на то, что он пытается подключиться к порту 80.

@DaveSatchell Я изменил его на robot.http(«http://localhost:3000») , и это сработало. Немного смущен, что это была такая тривиальная проблема . большое спасибо!

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

Источник

Клиент TCPIP — EHOSTUNREACH (нет маршрута к хосту)

Я пытаюсь разработать клиент-серверное приложение TCP/IP. У меня есть сервер, работающий на моем ПК, и клиентское приложение работает на мобильном телефоне. Они оба находятся в одной сети Wi-Fi, но я не могу установить между ними соединение. При отладке клиентского приложения для Android возникла следующая ошибка:

Код, который я использую:

Что я делаю не так?

задан 21 сен ’12, 00:09

разблокируйте брандмауэр на стороне вашего компьютера, скорее всего, порт заблокирован или . подтвердите и убедитесь, что ваш частный IP-адрес находится в диапазоне 192.168.xy, а DHCP на Wi-Fi действительно передает тот же диапазон сетевых адресов 192.168. .xy на ваше устройство Android. — t0mm13b

7 ответы

Ошибка отсутствия маршрута указывает на то, что при попытке установить TCP-соединение произошел сбой соединения, поскольку программное обеспечение базового протокола не смогло найти маршрут сетевого узла к сетевому узлу к назначенному целевому узлу.

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

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

Похоже, это устройство Android, поэтому в первую очередь нужно убедиться, что у вас есть подключение, будь то Wi-Fi или сотовая связь. Другим было бы убедиться, что Wi-Fi или сотовая связь включены и работают.

Указанный вами IP-адрес обычно находится в частной подсети. Поэтому нужно проверить, находится ли устройство, к которому вы пытаетесь подключиться, в той же подсети, что и ваше устройство.

Цитата из комментария к Android пользователя detenson

Комментарий пользователя detenson от 13 мая 2017 г. добавляет эту дополнительную информацию, относящуюся к Android, и сообщения об ошибках, представленные в публикации.

Источник

Клиент TCPIP-EHOSTUNREACH (нет маршрута к хосту)

Я пытаюсь разработать приложение TCP/IP клиентского сервера. У меня есть сервер, работающий на моем компьютере, и клиентское приложение работает на мобильном телефоне. Они оба находятся в одной Wi-Fi сети, но я не могу установить связь между ними. При отладке клиентского приложения Android обнаружилась следующая ошибка:

код, который я использую:

что я делаю не так?

6 ответов

ошибка no route указывает, что при попытке подключения TCP соединение не удалось, поскольку базовое программное обеспечение протокола не смогло найти сетевой узел для сетевого узла маршрута к назначенному целевому узлу.

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

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

Это похоже на Android-устройство, поэтому первое, что нужно сделать, это убедиться, что у вас есть подключение, будь то WiFi или сотовый. Другим было бы убедиться, что WiFi или сотовый включен и работает.

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

Это похоже на сетевую проблему, а не на проблему Java. Либо:

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

(сообщение «No route to host» предполагает, что это первая проблема, но брандмауэры иногда настроены на предоставление вводящие в заблуждение ответы на нежелательный трафик.)

в любом случае, вам было бы лучше искать сайт о том, как настроить и / или сети и маршрутизацию.

Привет у меня была такая же проблема на моем mac и запуск приложения на устройстве android. Мне пришлось сделать следующие 2 вещи, чтобы заставить его работать:

  1. выключите брандмауэр на mac
  2. включить инфракрасный приемник (система Pref > безопасность > Брандмауэр > дополнительно)

и это сработало!

Я сталкиваюсь с той же проблемой, когда я разработал android-приложение для связи с Java desktop server, чтобы решить эту проблему, просто отключите usb-кабель, который соединяет телефон android с ПК.

загрузите приложение ping на свой телефон и попробуйте выполнить ping ip-адрес сервера, если он в порядке . при использовании apache поместите локальный IP-адрес машины в httpd.conf конфигурационный файл.

хост недоступен, просто так. Однако, если все в порядке (хорошо настроенный узел / сеть, хороший сигнал wifi. ) Вы можете заставить процесс с помощью ping serverIP (от телефона) или ping smartphone (от сервера).

Источник

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

Если я могу использовать ssh на порту 22 без проблем, что может здесь происходить, что :: connect () всегда не работает для этой конкретной пары машин?

Запуск ssh в подробном режиме дает:

[localMachine ~] ssh -v -p 22 remoteMachine
OpenSSH_3.9p1, OpenSSL 0.9.7a Feb 19 2003
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to remoteMachine [10.34.49.107] port 22.
debug1: Connection established.
debug1: identity file /home/WilliamKF/.ssh/identity type -1
debug1: identity file /home/WilliamKF/.ssh/id_rsa type 1
debug1: identity file /home/WilliamKF/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_4.3
debug1: match: OpenSSH_4.3 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_3.9p1
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'remoteMachine' is known and matches the RSA host key.
debug1: Found key in /home/WilliamKF/.ssh/known_hosts:47
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Next authentication method: gssapi-with-mic
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Authentications that can continue: publickey,gssapi-with-mic,password
debug1: Next authentication method: publickey
debug1: Trying private key: /home/WilliamKF/.ssh/identity
debug1: Offering public key: /home/WilliamKF/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 149
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.

Вот функция на стороне клиента:

void // virtual
Sender::connectTCP()
{
  // First build the feedback channel's socket & make it reuseable
  // so we don't get the nasty message.
  if (0 > (setFbSocket(socket(AF_INET, SOCK_STREAM, 0)))) {
    THROW_ERR("failed to create the command socket: ");
  }

  setSocketOptions();

  // Build the localIp address and bind it to the feedback socket.
  // Although it's not traditional for a client to bind the sending socket
  // to a the local address, we do it to prevent connect() from using an
  // ephemeral port which (our site's firewall may block). Also build the
  // remoteIp address.
  buildAddr(getTCPcommandLocalAddr(), getLocalHost().c_str(),
            getLocFbPort());
  deepBind(getFbSocket(), getTCPcommandLocalAddr());
  buildAddr(getTCPcommandRemoteAddr(), getRemoteHost().c_str(),
            getRemFbPort());

  // Connect to the receiver at the remote addr.  Make multiple attempts
  // when we get a connection refused errno (ECONNREFUSED).  ECONNREFUSED
  // means no one is listening at the other end ... which my be the result
  // of a race condition (i.e., we're calling connect before the server has
  // gotten to listen.)
  const int timeoutMinutes = 5;
  const int timeoutSeconds = timeoutMinutes * 60;
  int conCount = timeoutSeconds;

  while ((conCount > 0) &&
         (0 > ::connect(getFbSocket(),
                        (sockaddr*)&getTCPcommandRemoteAddr(),
                        sizeof(sockaddr)))) {
    switch (errno) {
      case ECONNREFUSED: {
        ::sleep(1);
        --conCount;
        // Warn every 15 seconds, but don't warn at 5 minutes exactly.
        if ((conCount % 15) == 0 && conCount) {
          clog << "Warning: The server connection"
               << " has been refused for "
               << timeFromSeconds(timeoutSeconds - conCount)
               << ", will continue to retry  for up to "
               << timeoutMinutes << " minutes.n"
               << "Perhaps ports " << getRemFbPort() << " and "
               << getRemDataPort()
               <<
            " are not being routed properly to the server or alternatively "
            "perhaps nothing on the server is listening to those ports?n";
        }
        continue;
      }
      case EHOSTUNREACH: {
        clog << "Error: Command connect failed: No route to host '"
             << getRemoteHost() << "'." << endl;
        throw;
      }
      default: {
        clog << "Error: Command connect failed: "
             << strerror(errno) << endl;
        throw;
      }
    }
  }
  if (conCount == 0) {
    clog << "Error: Command connect"
         << " continually refused after retrying for " << timeoutMinutes
         << " minutes: "
         << strerror(errno) << endl;

    throw;
  }

  setCmdBlocking();
  setDataBlocking();
  setFbIsConn(true);

  clog << "Application has connected to "
       << getRemoteHost() << ":" << getRemFbPort() << endl;
}

Я разрабатываю бота Slack (используя Хубот), а также приложение Rails, которое будет получать от него HTTP-запросы и обрабатывать их соответствующим образом. В основном, шаги высокого уровня того, что я хочу сделать, выглядят так:

  1. Неактивный пользователь отправляет боту триггерное слово (скажем, триггер «пока»).
  2. Hubot получает триггер, а затем отправляет запрос в приложение Rails.
  3. Приложение Rails помечает пользователя Slack как отсутствующего на рабочем месте.

Кажется, у меня есть какая-то проблема с маршрутизацией, потому что я получаю ошибку EHOSTUNREACH, когда пытаюсь выполнить этот поток с обоими загруженными приложениями (rails s для Rails и ./bin/hubot —adapter slack для Hubot). Я предполагаю, что Hubot вообще не может получить доступ к приложению Rails.
Я что-то упустил здесь? Какой URL-адрес мне нужно использовать, чтобы эти приложения могли отправлять запросы друг другу?

Я также пытался поменять местами 127.0.0.1:3000 на localhost:3000, но результат остался прежним.

Код Хубота

module.exports = (robot) ->
  robot.respond /bye/i, (res) ->
    res.reply('Later alligator')
    robot.logger.info 'Will proceed to clock out user'

    data = JSON.stringify({
      slack_user_id: res.message.user.id
    })
    robot.http("127.0.0.1:3000/")
      .header('Content-Type', 'application/json')
      .post(data) (err, resp, body) ->
        if err
          robot.logger.info "Encountered an error: #{err}"
        else
          robot.logger.info 'Successfully sent HTTP request to Rails app'

Результаты журнала, когда я отправляю триггерное слово боту

INFO Will proceed to clock out user
INFO Encountered an error: Error: connect EHOSTUNREACH 0.0.11.184:80 - Local (192.168.91.168:60029)

Журнал сервера Rails (это определенно порт 3000)

* Listening on tcp://localhost:3000

connect ehostunreach 0.0.31.153:80 #1514

Comments

carvalhoviniciusluiz commented May 1, 2018

Hi, I have a project with restify that sends data to an api with axios. When I start both apis locally the axios shows this message

I noticed that this post #1228 is similar to mine, but it’s closed.
How do you solve this?

environment

os: macOS
node: v8.9.3
npm: 5.5.1
axios: 0.18.0

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

koresar commented May 17, 2018

IP addresses can’t start with 0. Thus the EHOSTUNREACH error. See here for example: https://superuser.com/questions/665502/why-cant-ip-addresses-start-with-0-or-255

This issue should be closed.

carvalhoviniciusluiz commented May 18, 2018

but the local ip does not begin with 0. As it is construction, the project is raised in the local address (localhost or 127.0.0.1)

this message is not making sense because of this

koresar commented May 21, 2018

You’d need to find why the address is

mapleeit commented May 29, 2018 •

Hi @carvalhoviniciusluiz , I encountered this problem today. By doing debug, I found some reason may cause this problem.

It’s about your system bash/zsh proxy settings

axios will automatically detect your default proxys and use them.

the result of url.parse(‘localhost:8888’) :

get the wrong hostname

Then your dns will find this hostname, as a result, it returns 0.0.xx.xxx, which throw errors.

so just remove https_proxy and http_proxy and restart your terminal

Источник

Ошибка EHOSTUNREACH при отправке HTTP-запроса из приложения Hubot в приложение Rails локально

Я разрабатываю бота Slack (используя Хубот), а также приложение Rails, которое будет получать от него HTTP-запросы и обрабатывать их соответствующим образом. В основном, шаги высокого уровня того, что я хочу сделать, выглядят так:

  1. Неактивный пользователь отправляет боту триггерное слово (скажем, триггер «пока»).
  2. Hubot получает триггер, а затем отправляет запрос в приложение Rails.
  3. Приложение Rails помечает пользователя Slack как отсутствующего на рабочем месте.

Кажется, у меня есть какая-то проблема с маршрутизацией, потому что я получаю ошибку EHOSTUNREACH , когда пытаюсь выполнить этот поток с обоими загруженными приложениями ( rails s для Rails и ./bin/hubot —adapter slack для Hubot). Я предполагаю, что Hubot вообще не может получить доступ к приложению Rails. Я что-то упустил здесь? Какой URL-адрес мне нужно использовать, чтобы эти приложения могли отправлять запросы друг другу?

Я также пытался поменять местами 127.0.0.1:3000 на localhost:3000 , но результат остался прежним.

Код Хубота

Результаты журнала, когда я отправляю триггерное слово боту

Журнал сервера Rails (это определенно порт 3000)

Проверьте, что вы получаете в браузере с локальный: 3000, если это не работает, у вас, вероятно, проблемы с конфигурацией локальной сети. Если это сработает, попробуйте изменить код на robot.http(«http://localhost:3000») и обновите свой пост, указав результат. Ваше сообщение об ошибке, похоже, указывает на то, что он пытается подключиться к порту 80.

@DaveSatchell Я изменил его на robot.http(«http://localhost:3000») , и это сработало. Немного смущен, что это была такая тривиальная проблема . большое спасибо!

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

Источник

STACK: Error: connect EHOSTUNREACH #133

Comments

doublemint12 commented Apr 27, 2020

STACK: Error: connect EHOSTUNREACH

Just wanted to ask a quick question in regards to the issue I’m having when I’m trying to render my UX Design Nanodegree coursework.

I did a quick search for EHOSTUNREACH on Udacimak’s issues page but I couldn’t find anything. It seems like an API issue b/c it’s giving me some IP address that’s not mine. I do have Windscribe VPN downloaded but wasn’t using it on my Mac (Catalina).

If there is no solution for this then, is there a way for Udacimak to continue rendering and skip whatever it can’t render? My terminal shell output is shown below.

Desktop :

  • OS: [macOS Catalina]
  • Node version: ( v12.16.2 )
  • npm version: ( 6.14.4 )
  • Udacimak Version: ( v1.6.2 )
  • Browser [safari]

Course Information

  • UX Designer Nano-degree
  • Version: 1.0.0
  • Locale: en-us

Additional context
Lastly, will Udacimak continue to support older nano-degrees versions? It looks like it’s getting updated pretty frequently and I was wondering if older Udacimak versions get deprecated as well.

It looks like it’s gonna be a large size when it gets fully rendered so I saved the original Json data I downloaded from running «udacimak download nd578».

I was hoping I can render my nanodegree version (v1.0.0) when I no longer have the access to my account.

Also, thank you so much for putting this out for us!
It’s super interesting to learn how it works.

Thank you very much for your time.

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

Источник

Error: connect EHOSTUNREACH #34

Comments

KrX3D commented Nov 7, 2020 •

im getting this error:

openhab.0 2020-11-07 22:27:43.236 error (29781) Cannot get answer from «http://192.168.0.101:8080/rest/items?recursive=false»: Error: connect EHOSTUNREACH 192.168.0.101:8080

but going to «http://192.168.0.101:8080/rest/items?recursive=false» via browser i get a list of my items so what is wrong?

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

Apollon77 commented Nov 8, 2020

did you teally tried it from the same host as iobroker runs on? Maybe try via «wget» or «curl» from that host

KrX3D commented Nov 8, 2020

i have a NAS with Unraid as OS, on it i run different docker images.

iobroker docker image has the ip 192.168.0.113 Port 8081
openhab docker image has the ip 192.168.0.101 Port 8080

when i start the openhab adapter i get the error:

openhab.0 2020-11-08 09:55:36.069 error (31404) Cannot get answer from «http://192.168.0.101:8080/rest/items?recursive=false»: Error: connect EHOSTUNREACH 192.168.0.101:8080

but when i access the link from this error «http://192.168.0.101:8080/rest/items?recursive=false» via my notebook browser i see this:

Apollon77 commented Nov 9, 2020

Network is different . sorry but here you need to see why the openhab docker container can not reached from the second docker container . this has nothing to d with the adapter. I think the Forum or docker support forums can help more.

KrX3D commented Nov 10, 2020

thanks for the hint, i changed the ip of the openhab docker image also to 192.168.0.113 and now it works

Источник

receiving «connect EHOSTUNREACH 169.254.169.254:80» when following simple README #389

Comments

mreinigjr commented Sep 16, 2019

Environment details

  • OS: Ubuntu 18 LTS
  • Node.js version: 10.16.0
  • npm version: 6.11.3
  • @google-cloud/logging-winston version: 2.0.1
  • winston version: 3.2.1

Steps to reproduce

  1. Use a non-GCP server/environment.
  2. Follow this: https://github.com/googleapis/nodejs-logging-winston/blob/master/samples/quickstart.js

This issue is very similar if not identical to:
googleapis/nodejs-logging-bunyan#353

The only resolution I have found so far is to revert back to logging-winston version 0.11.1. Under the environment above, everything then works.

I am seeing this issues whether I set the GOOGLE_APPLICATION_CREDENTIALS env variable or specify the projectId and keyFilename or specify projectId and credentials when creating the LoggingWinston object. So all 3 ways fail on v1.0.0+, but all 3 work on v0.11.1.

I have seen the error appear two different ways, with the first type of error message appearing from following the above steps.

Here is an alternative error message that we are seeing using the same environment outlined above, but on a remote server. I do not have reproducible steps for this error message, but this was the first error message we saw before digging deeper. The below error message lead us to the reproducible error message above.

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

Источник

Понравилась статья? Поделить с друзьями:
  • Error conflicting types for си
  • Error conflicted subnet addresses
  • Error configuring sdk pycharm
  • Error configuring s3 backend no valid credential sources for s3 backend found
  • Error constexpr does not name a type