All right—I’ve figured it out.
First off, @Mark B was right—the issue was that I hadn’t yet made the database itself publicly accessible via the VPC security group of which it was a member. To do this, from the database detail screen in AWS, I:
- clicked (what for me was the one and only) link beneath the «VPC security groups» of the database’s dashboard, which directed me to the EC2 Security Groups screen
- clicked the security group link related to my database, which directed me to that group’s detail page
- clicked the «Edit inbound rules» button which directed me to the «Edit inbound rules» screen
- clicked the «Add rule» button, which caused a table row containing the following columns: «Type», «Protocol,» «Port Range,» «Source,» «Description — optional»
- selected «PostgreSQL» for the «Type» column, which caused the values of «TCP» and «5432» to populate the «Protocol» and «Port range» columns respectively, entered my machine’s IP address («123.456.789.012/32»—no quotes and no parentheses), and left «Description — optional» blank, because, well, it’s optional.
Finally, I guess I’d forgotten to explicitly name the database, and so my attempts to enter what for me was ostensibly the database’s name (that is, «database-1») resulted in a connection error indicating that «database-1» does not exist. So, for the sake of ease and simply verifying my database connection, I entered «postgres» as the database name in my database client (I’m presently using DataGrip), because «postgres» is the de facto name of a postgreSQL database.
And that should work. I’m sure this is all no-brainer stuff to those more experienced with AWS, but it’s new to me and presumably to many others.
Thanks again, @Mark B, for sending me down the right path.
I have some severe problems with connecting from DBVisualizer (8.0.9) to a PostgreSQL server which is running in the same LAN. DBVis is Java-based thus uses JDBC for connection. Connecting from PGAdmin works like a charm — only DBVis connection via JDBC isn’t. And I need that to be solved!
Specs:
My PC: Ubuntu 12.04 LTS (64Bit), IP: 192.168.110.193
Server OS: Suse LINUX Enterprise Server 11, IP: 192.168.110.12
Postgresql server version: 9.1
Java VM: Java HotSpot(TM) 64-Bit Server VM
Java Version: 1.6.0_33
Java Vendor: Sun Microsystems Inc.
OS Name: Linux
OS Arch: amd64
OS Version: 3.2.0-25-generic
When starting a connection, I’m getting a «Connecting…» message and after ~5 minutes of waiting the following error message appears in the connection window:
"An error occurred while establishing the connection:
Long Message:
The connection attempt failed.
Details:
Type: org.postgresql.util.PSQLException
SQL State: 08001"
In the debug console I get:
12:04:57 [DEBUG pool-2-thread-8 D.ā] RootConnection: Driver.acceptsURL("jdbc:postgresql://192.168.110.12:5432/MYDATABASE")
12:04:57 [DEBUG pool-2-thread-8 D.ā] RootConnection: Driver.connect("jdbc:postgresql://192.168.110.12:5432/MYDATABASE", {user=******, password=******})
12:24:58 [DEBUG pool-2-thread-8 D.ā] RootConnection: EXCEPTION -> org.postgresql.util.PSQLException: The connection attempt failed.
The debugging information of the JDBC driver is also provided:
org.postgresql.util.PSQLException: The connection attempt failed.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:150)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:66)
at org.postgresql.jdbc2.AbstractJdbc2Connection.(AbstractJdbc2Connection.java:125)
at org.postgresql.jdbc3.AbstractJdbc3Connection.(AbstractJdbc3Connection.java:30)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.(AbstractJdbc3gConnection.java:22)
at org.postgresql.jdbc4.AbstractJdbc4Connection.(AbstractJdbc4Connection.java:30)
at org.postgresql.jdbc4.Jdbc4Connection.(Jdbc4Connection.java:24)
at org.postgresql.Driver.makeConnection(Driver.java:393)
at org.postgresql.Driver.connect(Driver.java:267)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at com.onseven.dbvis.d.B.D.ā(Z:1548)
at com.onseven.dbvis.d.B.F$A.call(Z:278)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
For convenience the relevant part of the server’s pg_hba.conf:
#"local" is for Unix domain socket connections only
local all all peer
#IPv4 local connections:
host all all 192.168.110.0/24 md5
#IPv6 local connections:
host all all ::1/128 md5
And the relevant parts of the postgresql.conf:
# - Connection Settings -
listen_addresses = '*' # what IP address(es) to listen on;
# comma-separated list of addresses;
# defaults to 'localhost', '*' = all
# (change requires restart)
#port = 5432 # (change requires restart)
max_connections = 100 # (change requires restart)
# Note: Increasing max_connections costs ~400 bytes of shared memory per
# connection slot, plus lock space (see max_locks_per_transaction).
#superuser_reserved_connections = 3 # (change requires restart)
#unix_socket_directory = '' # (change requires restart)
#unix_socket_group = '' # (change requires restart)
#unix_socket_permissions = 0777 # begin with 0 to use octal notation
# (change requires restart)
#bonjour = off # advertise server via Bonjour
# (change requires restart)
#bonjour_name = '' # defaults to the computer name
# (change requires restart)
# - Security and Authentication -
#authentication_timeout = 1min # 1s-600s
#ssl = off # (change requires restart)
#ssl_ciphers = 'ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH' # allowed SSL ciphers
# (change requires restart)
#ssl_renegotiation_limit = 512MB # amount of data between renegotiations
#password_encryption = on
#db_user_namespace = off
# Kerberos and GSSAPI
#krb_server_keyfile = ''
#krb_srvname = 'postgres' # (Kerberos only)
#krb_caseins_users = off
# - TCP Keepalives -
# see "man 7 tcp" for details
#tcp_keepalives_idle = 0 # TCP_KEEPIDLE, in seconds;
# 0 selects the system default
#tcp_keepalives_interval = 0 # TCP_KEEPINTVL, in seconds;
# 0 selects the system default
#tcp_keepalives_count = 0 # TCP_KEEPCNT;
# 0 selects the system default
I can connect to Postgres via PgAdmin, but I can’t connect via DataGrip.
I click on Test Connection button but it fails, error is that;
[08001] The connection attempt failed. The connection attempt failed.
By the way i’m using vpn but pgAdmin can connecting.
- postgresql
- jetbrains-ide
- datagrip
asked Mar 2, 2022 at 12:50
4
-
Do you have any firewall on your machine? What is PG server version you are connecting to? Please check idea.log file from Help -> Show log in… — there could be more verbose error.
Mar 2, 2022 at 14:41
-
Seems that something is wrong with your server
Mar 2, 2022 at 14:41
-
thanks all of your advice, yes, i’m using vpn but pgAdmin can connecting
Mar 13, 2022 at 11:58
-
@MehmetTopçu I meet the same case. My app in my local machine can connect to pg with no problem while DataGrip failed with the same error. If I config my VPN disabling the set as system proxy option, then DataGrip backed to work like a chram.
Jun 5, 2022 at 19:03
1 Answer
I solved the problem as below,
The window with the test button has an advanced tab
I added this code to VM options:
-Djava.net.preferIPv4Stack=true
answered Mar 13, 2022 at 12:10
2
-
Hello. I have the same issue but this does not solve my problem. Any other insight you might be able to share?
Jan 10 at 17:15
-
This is my Error:
DBMS: Case sensitivity: plain=mixed, delimited=exact Driver: (ver. , JDBC) Effective version: PostgreSQL (ver. 0.0) The connection attempt failed.Jan 10 at 17:15
All right—I’ve figured it out.
First off, @Mark B was right—the issue was that I hadn’t yet made the database itself publicly accessible via the VPC security group of which it was a member. To do this, from the database detail screen in AWS, I:
- clicked (what for me was the one and only) link beneath the «VPC security groups» of the database’s dashboard, which directed me to the EC2 Security Groups screen
- clicked the security group link related to my database, which directed me to that group’s detail page
- clicked the «Edit inbound rules» button which directed me to the «Edit inbound rules» screen
- clicked the «Add rule» button, which caused a table row containing the following columns: «Type», «Protocol,» «Port Range,» «Source,» «Description — optional»
- selected «PostgreSQL» for the «Type» column, which caused the values of «TCP» and «5432» to populate the «Protocol» and «Port range» columns respectively, entered my machine’s IP address («123.456.789.012/32»—no quotes and no parentheses), and left «Description — optional» blank, because, well, it’s optional.
Finally, I guess I’d forgotten to explicitly name the database, and so my attempts to enter what for me was ostensibly the database’s name (that is, «database-1») resulted in a connection error indicating that «database-1» does not exist. So, for the sake of ease and simply verifying my database connection, I entered «postgres» as the database name in my database client (I’m presently using DataGrip), because «postgres» is the de facto name of a postgreSQL database.
And that should work. I’m sure this is all no-brainer stuff to those more experienced with AWS, but it’s new to me and presumably to many others.
Thanks again, @Mark B, for sending me down the right path.
All right—I’ve figured it out.
First off, @Mark B was right—the issue was that I hadn’t yet made the database itself publicly accessible via the VPC security group of which it was a member. To do this, from the database detail screen in AWS, I:
- clicked (what for me was the one and only) link beneath the «VPC security groups» of the database’s dashboard, which directed me to the EC2 Security Groups screen
- clicked the security group link related to my database, which directed me to that group’s detail page
- clicked the «Edit inbound rules» button which directed me to the «Edit inbound rules» screen
- clicked the «Add rule» button, which caused a table row containing the following columns: «Type», «Protocol,» «Port Range,» «Source,» «Description — optional»
- selected «PostgreSQL» for the «Type» column, which caused the values of «TCP» and «5432» to populate the «Protocol» and «Port range» columns respectively, entered my machine’s IP address («123.456.789.012/32»—no quotes and no parentheses), and left «Description — optional» blank, because, well, it’s optional.
Finally, I guess I’d forgotten to explicitly name the database, and so my attempts to enter what for me was ostensibly the database’s name (that is, «database-1») resulted in a connection error indicating that «database-1» does not exist. So, for the sake of ease and simply verifying my database connection, I entered «postgres» as the database name in my database client (I’m presently using DataGrip), because «postgres» is the de facto name of a postgreSQL database.
And that should work. I’m sure this is all no-brainer stuff to those more experienced with AWS, but it’s new to me and presumably to many others.
Thanks again, @Mark B, for sending me down the right path.
Creating my container as:
public static PostgreSQLContainer<?> container = new PostgreSQLContainer<>("postgres:latest");
static {
container.start();
System.setProperty("driver-class-name", container.getDriverClassName());
System.setProperty("spring.datasource.url", container.getJdbcUrl());
System.setProperty("spring.datasource.username", container.getUsername());
System.setProperty("spring.datasource.password", container.getPassword());
}
I’m trying to enter debug mode after start and check connection, however I keep getting
[08001] The connection attempt failed. java.io.EOFException.
Full exception trace:
org.postgresql.util.PSQLException: The connection attempt failed.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:292)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:211)
at org.postgresql.Driver.makeConnection(Driver.java:458)
at org.postgresql.Driver.connect(Driver.java:260)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.lenovo.edge.controller.UploadControllerTest.whenSelectQueryExecuted_thenResulstsReturned(UploadControllerTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.io.EOFException
at org.postgresql.core.PGStream.receiveChar(PGStream.java:337)
at org.postgresql.core.v3.ConnectionFactoryImpl.enableSSL(ConnectionFactoryImpl.java:411)
at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:135)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:192)
... 29 more
So it’s pretty obvious that my application cannot connect to it as well.
Any suggestions?
asked Feb 21, 2020 at 11:05
Tyulpan TyulpanTyulpan Tyulpan
7141 gold badge7 silver badges17 bronze badges
7
Answering my own question, the problem was container was not able to receive connections, I’m not sure actually why, cos config looks fine for me, but working solution is to initialize container as https://www.testcontainers.org/modules/databases/#database-containers-launched-via-jdbc-url-scheme
So here is example of working solution for me, hope it can help to somebody:
@ActiveProfiles("test")
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, properties = {
"spring.datasource.url=jdbc:tc:postgresql:12.2:///test?TC_INITSCRIPT=init.sql",
"spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver"
})
abstract class AbstractIntegrationTestCase {
public static GenericContainer<?> container = new PostgreSQLContainer<>("postgres:12.2");
static {
container.start();
}
@Autowired
protected TestRestTemplate restTemplate;
}
answered Feb 24, 2020 at 8:13
Tyulpan TyulpanTyulpan Tyulpan
7141 gold badge7 silver badges17 bronze badges
Когда я пытаюсь подключиться к экземпляру базы данных PostgreSQL, которую я создал согласно руководству AWS «Создание и подключение к базе данных PostgreSQL с Amazon RDS», расположенному здесь ( https://aws.amazon.com/getting-started/tutorials/create-connect-postgresql-db/ ), Я получаю сообщение об ошибке:
[08001] Попытка подключения не удалась. java.net.SocketTimeoutException: время ожидания подключения истекло.
База данных настроена на разрешение входящего и исходящего трафика на всех портах и со всех IP-адресов. Я совершенно не понимаю, как заставить это работать, и обратился в службу поддержки AWS за их предложениями, но пока что все, что я сделал, — это следовал инструкциям, предписанным в руководстве по AWS, — безрезультатно.
Кто-нибудь знает, в чем может быть проблема?
Изменить: я должен упомянуть, что весь мой URL-адрес хоста, номер порта, имя базы данных и т. Д. Были правильно введены в DataGrip, поэтому ни одна из вышеперечисленных проблем не является проблемой.
1 ответ
Лучший ответ
Хорошо — я понял.
Во-первых, @Mark B был прав — проблема заключалась в том, что я еще не сделал саму базу данных общедоступной через группу безопасности VPC, членом которой он был. Для этого на подробном экране базы данных в AWS я:
- нажал (что для меня было единственной) ссылку под «Группы безопасности VPC» на панели управления базы данных, которая направила меня на экран «Группы безопасности EC2»
- щелкнул ссылку группы безопасности, относящуюся к моей базе данных, которая направила меня на страницу сведений об этой группе
- нажал кнопку «Изменить правила для входящих подключений», которая направила меня на экран «Изменить правила для входящих подключений».
- нажал кнопку «Добавить правило», в результате чего появилась строка таблицы, содержащая следующие столбцы: «Тип», «Протокол», «Диапазон портов», «Источник», «Описание — необязательно»
- выбрал «PostgreSQL» для столбца «Тип», в результате чего значения «TCP» и «5432» заняли соответственно столбцы «Протокол» и «Диапазон портов», ввел IP-адрес моей машины («123.456.789.012/32» — без кавычек и скобок) и оставил поле «Описание — необязательно» пустым, потому что это необязательно.
Наконец, я думаю, что забыл явно назвать базу данных, и поэтому мои попытки ввести то, что для меня было якобы именем базы данных (то есть «база данных-1»), привели к ошибке соединения, указывающей, что «база данных-1» не существует. Итак, для простоты и простой проверки подключения к базе данных я ввел «postgres» в качестве имени базы данных в моем клиенте базы данных (в настоящее время я использую DataGrip), потому что «postgres» — это фактическое имя базы данных postgreSQL.
И это должно сработать. Я уверен, что это несложно для тех, кто более опытен с AWS, но это ново для меня и, предположительно, для многих других.
Еще раз спасибо, @Mark B, за то, что направил меня по правильному пути.
2
Michael P.
11 Дек 2020 в 01:52
Problem
When using PostgreSQL in the DQIT Web Application, we have encountered the following error:
Message: java.io.EOFExceptionDetails: java.io.EOFException at com.ataccama.dqc.commons.serialize.Serialize.read(Serialize.java:497) at com.ataccama.dqc.commons.serialize.Serialize.deserializeString(Serialize.java:387) at com.ataccama.epp.internal.core.data.db.dao.DbIssueBean.loadCustomAttrs(DbIssueBean.java:407) at com.ataccama.epp.internal.core.data.db.dao.IssueDao.makeIssue(IssueDao.java:172) at com.ataccama.epp.internal.core.data.db.dao.IssueDao.findIssues(IssueDao.java:234) ... at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)
Solution
This exception is caused by an outdated PostgreSQL JDBC driver used to connect to the PostgreSQL database. To resolve the problem, download and install the latest version of the PostgreSQL JDBC driver for the particular version of the PostgreSQL database. The version of the PostgreSQL database is displayed under the Properties tab when you click on the database connection under File Explorer > Databases > [Connection name] See the screenshot below.
Related articles
Hello,
i’m unable to connect to a postgres database through ssh tunnel. The connection is established and authentication succeeded but i’m disconnected. Here is the stacktrace :
2017-01-17 16:40:27.585 — DBeaver 3.8.3 is starting
2017-01-17 16:40:27.588 — Install path: ‘file:/C:/Program Files/dbeaver/’
2017-01-17 16:40:27.588 — Instance path: ‘file:/C:/Users/dimitri/.dbeaver/’
2017-01-17 16:40:27.590 — Memory available 123Mb/1796Mb
2017-01-17 16:40:27.594 — Starting RMI server at 59302
2017-01-17 16:40:27.646 — Initialize display
2017-01-17 16:40:28.774 — Initializing DBeaver 3.8.3
2017-01-17 16:40:28.778 — Host plugin: org.jkiss.dbeaver.core.application 3.8.3
2017-01-17 16:40:28.781 — Initialize Core…
2017-01-17 16:40:28.946 — Core initialized (165ms)
2017-01-17 16:40:28.949 — Configure workbench window
2017-01-17 16:40:29.023 — Create actions
2017-01-17 16:40:29.368 — Initialize workbench window
2017-01-17 16:40:29.387 — Finish initialization
2017-01-17 16:40:30.555 — Connect with ‘PostgreSQL — test’ (postgres-jdbc-1598c9d3ea8-43254cdf6a1bbb1)
2017-01-17 16:40:30.727 — Connected (postgres-jdbc-1598c9d3ea8-43254cdf6a1bbb1)
2017-01-17 16:40:36.691 — Connect with ‘jdbc:postgresql://dev.server.local:5432/test’ (postgres-jdbc-15996e6e5d1-88ac6223155bb8dc)
2017-01-17 16:40:36.810 — Instantiate SSH tunnel
2017-01-17 16:40:36.817 — Connect to tunnel host
2017-01-17 16:40:36.818 — SSH INFO: Connecting to dev.server.local port 22
2017-01-17 16:40:36.822 — SSH INFO: Connection established
2017-01-17 16:40:36.839 — SSH INFO: Remote version string: SSH-2.0-OpenSSH_6.6.1
2017-01-17 16:40:36.840 — SSH INFO: Local version string: SSH-2.0-JSCH-0.1.53
2017-01-17 16:40:36.842 — SSH INFO: CheckCiphers: aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,3des-ctr,arcfour,arcfour128,arcfour256
2017-01-17 16:40:36.859 — SSH INFO: aes256-ctr is not available.
2017-01-17 16:40:36.860 — SSH INFO: aes192-ctr is not available.
2017-01-17 16:40:36.861 — SSH INFO: aes256-cbc is not available.
2017-01-17 16:40:36.862 — SSH INFO: aes192-cbc is not available.
2017-01-17 16:40:36.863 — SSH INFO: CheckKexes: diffie-hellman-group14-sha1,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521
2017-01-17 16:40:36.902 — SSH INFO: CheckSignatures: ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
2017-01-17 16:40:36.906 — SSH INFO: SSH_MSG_KEXINIT sent
2017-01-17 16:40:36.907 — SSH INFO: SSH_MSG_KEXINIT received
2017-01-17 16:40:36.908 — SSH INFO: kex: server: curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
2017-01-17 16:40:36.911 — SSH INFO: kex: server: ssh-rsa,ecdsa-sha2-nistp256,ssh-ed25519
2017-01-17 16:40:36.913 — SSH INFO: kex: server: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
2017-01-17 16:40:36.917 — SSH INFO: kex: server: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,rijndael-cbc@lysator.liu.se
2017-01-17 16:40:36.922 — SSH INFO: kex: server: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
2017-01-17 16:40:36.928 — SSH INFO: kex: server: hmac-md5-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-64-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-ripemd160-etm@openssh.com,hmac-sha1-96-etm@openssh.com,hmac-md5-96-etm@openssh.com,hmac-md5,hmac-sha1,umac-64@openssh.com,umac-128@openssh.com,hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-sha1-96,hmac-md5-96
2017-01-17 16:40:36.934 — SSH INFO: kex: server: none,zlib@openssh.com
2017-01-17 16:40:36.936 — SSH INFO: kex: server: none,zlib@openssh.com
2017-01-17 16:40:36.937 — SSH INFO: kex: server:
2017-01-17 16:40:36.938 — SSH INFO: kex: server:
2017-01-17 16:40:36.939 — SSH INFO: kex: client: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1
2017-01-17 16:40:36.942 — SSH INFO: kex: client: ssh-rsa,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
2017-01-17 16:40:36.944 — SSH INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc
2017-01-17 16:40:36.946 — SSH INFO: kex: client: aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc
2017-01-17 16:40:36.947 — SSH INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
2017-01-17 16:40:36.949 — SSH INFO: kex: client: hmac-md5,hmac-sha1,hmac-sha2-256,hmac-sha1-96,hmac-md5-96
2017-01-17 16:40:36.950 — SSH INFO: kex: client: none
2017-01-17 16:40:36.951 — SSH INFO: kex: client: none
2017-01-17 16:40:36.952 — SSH INFO: kex: client:
2017-01-17 16:40:36.953 — SSH INFO: kex: client:
2017-01-17 16:40:36.953 — SSH INFO: kex: server->client aes128-ctr hmac-md5 none
2017-01-17 16:40:36.955 — SSH INFO: kex: client->server aes128-ctr hmac-md5 none
2017-01-17 16:40:36.960 — SSH INFO: SSH_MSG_KEX_ECDH_INIT sent
2017-01-17 16:40:36.961 — SSH INFO: expecting SSH_MSG_KEX_ECDH_REPLY
2017-01-17 16:40:36.970 — SSH INFO: ssh_rsa_verify: signature true
2017-01-17 16:40:36.973 — SSH WARN: Permanently added ‘dev.server.local’ (RSA) to the list of known hosts.
2017-01-17 16:40:36.975 — SSH INFO: SSH_MSG_NEWKEYS sent
2017-01-17 16:40:36.976 — SSH INFO: SSH_MSG_NEWKEYS received
2017-01-17 16:40:36.979 — SSH INFO: SSH_MSG_SERVICE_REQUEST sent
2017-01-17 16:40:36.980 — SSH INFO: SSH_MSG_SERVICE_ACCEPT received
2017-01-17 16:40:36.987 — SSH INFO: Authentications that can continue: publickey
2017-01-17 16:40:36.989 — SSH INFO: Next authentication method: publickey
2017-01-17 16:40:37.280 — SSH INFO: Authentication succeeded (publickey).
2017-01-17 16:40:37.543 — Connection failed (postgres-jdbc-15996e6e5d1-88ac6223155bb8dc)
2017-01-17 16:40:37.546 — SSH INFO: Disconnecting from dev.server.local port 22
2017-01-17 16:40:37.548 — SSH INFO: Caught an exception, leaving main loop due to Socket closed
2017-01-17 16:40:37.560 — org.jkiss.dbeaver.model.exec.DBCConnectException: La tentative de connexion a échoué.
org.jkiss.dbeaver.model.exec.DBCConnectException: La tentative de connexion a échoué.
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.openConnection(JDBCDataSource.java:173)
at org.jkiss.dbeaver.ext.postgresql.model.PostgreDataSource.openConnection(PostgreDataSource.java:352)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCExecutionContext.connect(JDBCExecutionContext.java:73)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.(JDBCDataSource.java:99)
at org.jkiss.dbeaver.ext.postgresql.model.PostgreDataSource.(PostgreDataSource.java:77)
at org.jkiss.dbeaver.ext.postgresql.PostgreDataSourceProvider.openDataSource(PostgreDataSourceProvider.java:97)
at org.jkiss.dbeaver.registry.DataSourceDescriptor.connect(DataSourceDescriptor.java:702)
at org.jkiss.dbeaver.runtime.jobs.ConnectJob.run(ConnectJob.java:74)
at org.jkiss.dbeaver.ui.dialogs.connection.ConnectionWizard$ConnectionTester.run(ConnectionWizard.java:222)
at org.jkiss.dbeaver.model.runtime.AbstractJob.run(AbstractJob.java:103)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
Caused by: org.postgresql.util.PSQLException: La tentative de connexion a échoué.
at org.postgresql.Driver$ConnectThread.getResult(Driver.java:355)
at org.postgresql.Driver.connect(Driver.java:279)
at org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource.openConnection(JDBCDataSource.java:159)
… 10 more
Caused by: java.io.EOFException
at org.postgresql.core.PGStream.receiveChar(PGStream.java:282)
at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:421)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:217)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:51)
at org.postgresql.jdbc.PgConnection.(PgConnection.java:215)
at org.postgresql.Driver.makeConnection(Driver.java:404)
at org.postgresql.Driver.access$100(Driver.java:52)
at org.postgresql.Driver$ConnectThread.run(Driver.java:314)
at java.lang.Thread.run(Unknown Source)
2017-01-17 16:41:39.686 — Shutdown Core…
2017-01-17 16:41:39.911 — Shutdown completed in 225ms
The error is not very clear, thanks for your help.
The java.io.EOFException is a checked exception in Java that occurs when an end of file or end of stream is reached unexpectedly during input. This exception is mainly used by data input streams to signal end of stream.
Since EOFException is a checked exception, it must be explicitly handled in methods that can throw this exception — either by using a try-catch block or by throwing it using the throws clause.
What Causes EOFException
While reading the contents of a file or stream using DataInputStream objects, if the end of the file or stream is reached unexpectedly, an EOFException is thrown. Methods of the DataInputStream class that are used to read data such as readBoolean(), readByte() and readChar() can throw this exception.
Many other input operations return a special value on end of file or stream rather than throwing an exception.
EOFException Example
Here’s an example of a EOFException thrown when trying to read all characters from an input file:
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class EOFExceptionExample {
public static void main(String[] args) {
DataInputStream inputStream = null;
try {
inputStream = new DataInputStream(new FileInputStream("myfile.txt"));
while (true) {
inputStream.readChar();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
In the above example, the contents of a file with the name myfile.txt are read in an infinite loop using the DataInputStream.readChar() method. When the readChar() method is called at the end of the file, an EOFException is thrown:
java.io.EOFException
at java.base/java.io.DataInputStream.readChar(DataInputStream.java:369)
at EOFExceptionExample.main(EOFExceptionExample.java:13)
How to Fix EOFException
Since EOFException is a checked exception, a try-catch block should be used to handle it. The try block should contain the lines of code that can throw the exception and the catch block should catch and handle the exception appropriately.
The above example can be updated to handle the EOFException in a try-catch block:
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
public class EOFExceptionExample {
public static void main(String[] args) {
DataInputStream inputStream = null;
try {
inputStream = new DataInputStream(new FileInputStream("myfile.txt"));
while (true) {
try {
inputStream.readChar();
} catch (EOFException eofe) {
System.out.println("End of file reached");
break;
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
Here, the inputStream.readChar() method call is placed in a try block and the EOFException is caught inside the catch block. When an EOFException occurs at the end of the file, it is handled and a break statement is used to break out of the loop.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!
Плагин Eclipse Hadoop сообщает «java.io.EOFException» при попытке подключения
- Я пытаюсь настроить Eclipse для Hadoop, используя этот страница
- Я использую банку плагина hadoop eclipse из здесь
- мой core-site.xml выглядит следующим образом:
<property> <name>fs.default.name</name> <value>hdfs://localhost:54310</value> <description>The name of the default file system. A URI whose scheme and authority determine the FileSystem implementation. The uri's scheme determines the config property (fs.SCHEME.impl) naming the FileSystem implementation class. The uri's authority is used to determine the host, port, etc. for a filesystem.</description> </property> </configuration>
- у моего mapred-site.xml есть следующие
<property> <name>mapred.job.tracker</name> <value>localhost:54311</value> <description>The host and port that the MapReduce job tracker runs at. If "local", then jobs are run in-process as a single map and reduce task. </description> </property>
-
Я настроил расположение hadoop в перспективе mapreduce в Eclipse как
Название локации: местная карта Reduce Master
- Хост: localhost
- порт: 54310
Мастер DFS
- Хост: localhost
- порт: 54311
-
Когда я пытаюсь подключиться, появляется сообщение об ошибке:
Ошибка: вызов localhost / 127.0.0.1: 54311 завершился неудачно при локальном исключении: java.io.EOFException
- Может ли кто-нибудь помочь мне решить эту проблему?
спасибо
3 ответы
У меня не было особых проблем. Гугл даст вам https://issues.apache.org/jira/browse/MAPREDUCE-1280
Используйте файл jar в своем затмении
$ cat mapred-site.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!-- Put site-specific property overrides in this file. -->
<configuration>
<property>
<name>mapred.job.tracker</name>
<value>localhost:8021</value>
</property>
</configuration>
Я установил мастер на 8021 и мастер DFS на 8020.
Я думаю, вы делаете ту же ошибку, что и я. Поменяйте местами номера портов в конфигурации eclipse, и он должен работать.
Создан 27 июля ’18, 04:07
К сожалению, плагин eclipse устарел, несколько месяцев назад мне удалось заставить его работать нормально, но это был кошмар, мне пришлось изменить там множество параметров: (
Я бы порекомендовал использовать веб-просмотр hdfs: перейдите в http://localhost:50070 или любой другой хост, на котором вы установили hadoop, и нажмите ссылку «Обзор файловой системы» (первая синяя ссылка сверху), вы увидите все, что вам нужно.
Создан 05 фев.
Я не думаю, что это проблема конфигурации HADOoop. Возможно, это было вызвано плагином hadoop eclipse.
Когда вы создаете проект hadoop, который не относится к типу Map / Reduce Project (тип проекта предоставлен плагином). Когда вы тестируете код MapReduce в этом проекте с помощью плагина hadoop eclipse, он генерирует исключение EOFException.
Тот же код и та же конфигурация hadoop успешно работает в проекте Map / Reduce.
ответ дан 20 авг.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
java
eclipse
apache
ubuntu
hadoop
or задайте свой вопрос.
All right—I’ve figured it out.
First off, @Mark B was right—the issue was that I hadn’t yet made the database itself publicly accessible via the VPC security group of which it was a member. To do this, from the database detail screen in AWS, I:
- clicked (what for me was the one and only) link beneath the «VPC security groups» of the database’s dashboard, which directed me to the EC2 Security Groups screen
- clicked the security group link related to my database, which directed me to that group’s detail page
- clicked the «Edit inbound rules» button which directed me to the «Edit inbound rules» screen
- clicked the «Add rule» button, which caused a table row containing the following columns: «Type», «Protocol,» «Port Range,» «Source,» «Description — optional»
- selected «PostgreSQL» for the «Type» column, which caused the values of «TCP» and «5432» to populate the «Protocol» and «Port range» columns respectively, entered my machine’s IP address («123.456.789.012/32»—no quotes and no parentheses), and left «Description — optional» blank, because, well, it’s optional.
Finally, I guess I’d forgotten to explicitly name the database, and so my attempts to enter what for me was ostensibly the database’s name (that is, «database-1») resulted in a connection error indicating that «database-1» does not exist. So, for the sake of ease and simply verifying my database connection, I entered «postgres» as the database name in my database client (I’m presently using DataGrip), because «postgres» is the de facto name of a postgreSQL database.
And that should work. I’m sure this is all no-brainer stuff to those more experienced with AWS, but it’s new to me and presumably to many others.
Thanks again, @Mark B, for sending me down the right path.
All right—I’ve figured it out.
First off, @Mark B was right—the issue was that I hadn’t yet made the database itself publicly accessible via the VPC security group of which it was a member. To do this, from the database detail screen in AWS, I:
- clicked (what for me was the one and only) link beneath the «VPC security groups» of the database’s dashboard, which directed me to the EC2 Security Groups screen
- clicked the security group link related to my database, which directed me to that group’s detail page
- clicked the «Edit inbound rules» button which directed me to the «Edit inbound rules» screen
- clicked the «Add rule» button, which caused a table row containing the following columns: «Type», «Protocol,» «Port Range,» «Source,» «Description — optional»
- selected «PostgreSQL» for the «Type» column, which caused the values of «TCP» and «5432» to populate the «Protocol» and «Port range» columns respectively, entered my machine’s IP address («123.456.789.012/32»—no quotes and no parentheses), and left «Description — optional» blank, because, well, it’s optional.
Finally, I guess I’d forgotten to explicitly name the database, and so my attempts to enter what for me was ostensibly the database’s name (that is, «database-1») resulted in a connection error indicating that «database-1» does not exist. So, for the sake of ease and simply verifying my database connection, I entered «postgres» as the database name in my database client (I’m presently using DataGrip), because «postgres» is the de facto name of a postgreSQL database.
And that should work. I’m sure this is all no-brainer stuff to those more experienced with AWS, but it’s new to me and presumably to many others.
Thanks again, @Mark B, for sending me down the right path.
Когда я пытаюсь подключиться к экземпляру базы данных PostgreSQL, которую я создал согласно руководству AWS «Создание и подключение к базе данных PostgreSQL с Amazon RDS», расположенному здесь ( https://aws.amazon.com/getting-started/tutorials/create-connect-postgresql-db/ ), Я получаю сообщение об ошибке:
[08001] Попытка подключения не удалась. java.net.SocketTimeoutException: время ожидания подключения истекло.
База данных настроена на разрешение входящего и исходящего трафика на всех портах и со всех IP-адресов. Я совершенно не понимаю, как заставить это работать, и обратился в службу поддержки AWS за их предложениями, но пока что все, что я сделал, — это следовал инструкциям, предписанным в руководстве по AWS, — безрезультатно.
Кто-нибудь знает, в чем может быть проблема?
Изменить: я должен упомянуть, что весь мой URL-адрес хоста, номер порта, имя базы данных и т. Д. Были правильно введены в DataGrip, поэтому ни одна из вышеперечисленных проблем не является проблемой.
1 ответ
Лучший ответ
Хорошо — я понял.
Во-первых, @Mark B был прав — проблема заключалась в том, что я еще не сделал саму базу данных общедоступной через группу безопасности VPC, членом которой он был. Для этого на подробном экране базы данных в AWS я:
- нажал (что для меня было единственной) ссылку под «Группы безопасности VPC» на панели управления базы данных, которая направила меня на экран «Группы безопасности EC2»
- щелкнул ссылку группы безопасности, относящуюся к моей базе данных, которая направила меня на страницу сведений об этой группе
- нажал кнопку «Изменить правила для входящих подключений», которая направила меня на экран «Изменить правила для входящих подключений».
- нажал кнопку «Добавить правило», в результате чего появилась строка таблицы, содержащая следующие столбцы: «Тип», «Протокол», «Диапазон портов», «Источник», «Описание — необязательно»
- выбрал «PostgreSQL» для столбца «Тип», в результате чего значения «TCP» и «5432» заняли соответственно столбцы «Протокол» и «Диапазон портов», ввел IP-адрес моей машины («123.456.789.012/32» — без кавычек и скобок) и оставил поле «Описание — необязательно» пустым, потому что это необязательно.
Наконец, я думаю, что забыл явно назвать базу данных, и поэтому мои попытки ввести то, что для меня было якобы именем базы данных (то есть «база данных-1»), привели к ошибке соединения, указывающей, что «база данных-1» не существует. Итак, для простоты и простой проверки подключения к базе данных я ввел «postgres» в качестве имени базы данных в моем клиенте базы данных (в настоящее время я использую DataGrip), потому что «postgres» — это фактическое имя базы данных postgreSQL.
И это должно сработать. Я уверен, что это несложно для тех, кто более опытен с AWS, но это ново для меня и, предположительно, для многих других.
Еще раз спасибо, @Mark B, за то, что направил меня по правильному пути.
2
Michael P.
11 Дек 2020 в 01:52
какие шаги я должен предпринять для решения ошибки:
java.net.UnknownHostException: Invalid hostname for server: local
я добавил новое имя виртуального хоста в эмуляторе Android, но результат возвращается к
java.net.UnknownHostException virtualhostname at
java.net.InetAddress.lookUpHostByName(InetAddress.java:506)
когда я набираю URL-адрес virtualhost на своем ПК, он работает на дисплее. Опять же, когда я запускал эмулятор и проверял Logcat, я не мог прочитать или проверить состояние HTTP, если 200, 202 или код ошибки. Он просто вернулся в UnknownHostException
12 ответов
на самом деле исключение говорит о том, что нет известного сервера с именем «local». Я предполагаю, что вы пытаетесь подключиться к локальному компьютеру. Попробуйте с именем хоста "localhost" вместо этого, или, возможно,127.0.0.1 или ::1 (последний-IPv6).
С javadocs:
брошенный, чтобы указать, что IP-адрес
хозяина определить не удалось.
127.0.0.1или ::1 или "localhost" всегда должен быть интерфейс loopback, поэтому, если это не сработает, я был бы очень удивлен.
если в вашей сети действительно есть сервер под названием «local» — проверьте настройки DNS или добавьте его в файл hosts.
у меня была такая же проблема на моем mac. Я нашел проблему, когда я позвала моя $HOSTNAME из терминала и он вернулся ping: cannot resolve myHostName: Unknown host.
решения:
- Do
echo $HOSTNAMEна ваш терминал. - любое имя хоста, которое он показывает (скажем
myHostName), попробуйте проверить это :ping myHostName. Если он вернетсяping: cannot resolve myHostName: Unknown hostзатем добавьте запись в свой . -
для редактирования
/etc/hostsфайл и добавить следующий:127.0.0.1 myHostName
надеюсь, что это помогает.
java.сеть.UnknownHostException: хост не разрешен:
брошенный, чтобы указать, что IP-адрес хоста не может быть определен.
это исключение также возникает, когда вы подключены к действительному wifi, но маршрутизатор не получает интернет. Его очень легко воспроизвести это:
- подключение к действительному wifi
- теперь удалите кабель из маршрутизатора, пока маршрутизатор подключен
вы обратите внимание на эту ошибку!!
вы не можете действительно решить эту проблему, вы можете только уведомить изящно пользователя. (что — то вроде — «невозможно установить связь»)
Это может произойти по разным причинам
1) Проверьте, подключен ли VPN, вы можете получить эту ошибку иногда, если да
» ваше имя хоста, localhost разрешает адрес обратной связи: 127.0.0.1; используя 10.xxx.1.193 Вместо (на интерфейсе cscotun0)»
2) Проверьте свой $ HOSTNAME
3) Попробуйте ping $HOSTNAME в командной строке, и если он не работает, настройте Системные настройки, чтобы ваш локальный хост отвечал на pings
5
автор: Sidharth N. Kashyap
отсутствует имя хоста. JBoss использует эту переменную среды ($HOSTNAME) при подключении к серверу.
[root@xyz ~]# echo $HOSTNAME
xyz
[root@xyz ~]# ping $HOSTNAME
ping: unknown host xyz
[root@xyz ~]# hostname -f
hostname: Unknown host
есть десятки вещей, которые могут вызвать это. Пожалуйста, прокомментируйте, если вы обнаружите новую причину.
для взлома, пока вы не сможете окончательно решить эту проблему на своем сервере, вы можете добавить строку до конца вашего файла / etc / hosts:
127.0.0.1 xyz.xxx.xxx.edu xyz
это не относится к вопросу, но этот вопрос появился, когда я гуглил для упомянутого UnknownHostException, и исправление не найдено нигде, поэтому я подумал, что добавлю ответ здесь.
исключение, которое постоянно получалось, было:
java.net.UnknownHostException: google.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
...
независимо от того, как я пытался подключиться к любому действительному хосту, печать его в терминале тоже не поможет. Все было правильно.
Решение
не зову trim() для строки хоста, содержащей пробелы. При написании прокси-сервера хост был получен из HTTP-заголовков с использованием split(":") точку с запятой для HOST заголовок. Это оставило пробелы и вызывает UnknownHostException как хост с пробелами не является допустимым хостом. Делать host = host.trim() на String host решить неоднозначный вопрос.
попробуйте следующее :
String url = "http://www.google.com/search?q=java";
URL urlObj = (URL)new URL(url.trim());
HttpURLConnection httpConn =
(HttpURLConnection)urlObj.openConnection();
httpConn.setRequestMethod("GET");
Integer rescode = httpConn.getResponseCode();
System.out.println(rescode);
Trim () URL
попытка подключения к локальному компьютеру.попробуйте вместо этого использовать имя хоста «localhost» или, возможно ::/ — последний-ipv6
1
автор: joshwayne diestro
попробуйте установить переменную среды SPARK_LOCAL_IP на ip-адрес (может быть localhost, т. е. ваш собственный ip-адрес), который вы хотите подключить. Е. Г.
$ export SPARK_LOCAL_IP=182.95.208.152
таким образом, вам не потребуется изменять существующие настройки linux.
Работал на меня, Хоуп тебе тоже помогает.
Connect ваш мобильный телефон с различным подключением wifi с другим поставщиком услуг.
Я не знаю точной проблемы, но я не мог подключиться к серверу с определенным поставщиком услуг, но он работает, когда я подключился к другому поставщику услуг. Так попробуй!
Если ваш файл / etc/localhosts имеет следующую запись:
Добавьте запись имени хоста, как показано ниже:
127.0.0.1 local host (add your hostname here)
::1 (add hostname here) (the last one is IPv6).
Это должно решить проблему.
вы должны заменить [] слишком!
пример [hostname] и вы должны заменить все это чем-то вроде этого:
jdbc:mysql://localhost:3306/openfire
Играя в Minecraft и вообще, пользуясь приложениями, написанными на Java Вы не раз могли столкнуться с ошибками (исключениями). В отличие от других языков программирования, Java жёстко заточена под использование ООП, потому при возникновении ошибки бросается исключение (объект содержащий сведения под ошибке). Его можно «поймать», дабы предпринять какие-то действия (допустим, вывести в лог). В случае майнкрафта, при возникновении исключения, создаётся краш-отчёт и работа игры завершается.
Понять исключения достаточно просто и вам для этого не понадобится специальное ПО для отладки.

Полная печать исключения состоит из 3-х частей:
- Исключение — имя класса ошибки. Классам обычно дают понятные человеку имена, достаточно знаний английского, чтобы понять значение.
- Сообщение — содержит более детальное описание ошибки. Может отсутствовать.
- Стек вызова — отражает ход работы программы (снизу вверх). Данная информация больше полезна разработчику, дабы понять, где именно возникла ошибка. Обычному пользователю данная информация может помочь понять, с чем связана ошибка (по именам классов и вызываемым функциям — методам).
Исключения могут иметь предков, что присутствует в данном примере (после «Caused by» идёт печать исключения-предка). Если вам не понятно исключение, возможно, стоит рассмотреть его предков — они могут содержать более понятное сообщение.
В данной теме я опишу наиболее часто встречающиеся ошибки, а также, какие действия следует или вовсе не следует предпринимать. Причин у ошибок множество и это не всегда повреждённые файлы игры (чего быть в принципе не может, поскольку лаунчер проверяет файлы игры).
При возникновении ошибок не спешите бежать переустанавливать Java и игру! Java — стабильный продукт. В большинстве случаев, ошибки возникают из-за неправильной настройки ОС; ошибок сети; неправильных драйверов.
org.lwjgl.LWJGLException: Pixel format not accelerated
Недоступно аппаратное ускорение графики. Описание ошибки (англ.)
Решение: Установите последнюю версию драйвера видеокарты.
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation/building failed
Не удаётся установить защищённое соединение из-за невозможности проверки SSL сертификата.
Что можно сделать:
- Эта ошибка может возникнуть из-за использования слишком старой версии Java. Рекомендуется регулярно обновлять ПО, чтобы иметь актуальный список корневых сертификатов.
- Виновником может быть антивирус, пытающийся «подсунуть» свой сертификат с целью прослушивания трафика. Настоятельно рекомендуется отключить в антивирусе проверку защищённых соединений (HTTPS/SSL/TLS) — это значительно снижает безопасность защищённых соединений и вызывает проблемы в работе приложений, использующие их.
java.net.SocketTimeOutException: Read timed out
Ошибка сети «время ожидания истекло». Здесь сложно установить виновника: проблема может быть как на стороне сервера, вашего провайдера или вызвана антивирусом.
Что можно сделать:
- Отключите антивирус и попробуйте выполнить запрос снова.
- Используйте другое подключение к интернету (другой провайдер; мобильный интернет; VPN; Wi-Fi соседей).
- Используйте VPN для обхода блокировки (цензуры) со стороны вашего интернет-провайдера.
java.net.ConnectException: Connection timed out: connect
Ошибка сети — не удалось установить соединение с хостом. Обычно виновником данной ошибки является Firewall (брандмауэр) или отсутствие интернета.
Что можно сделать:
- Проверьте наличие подключения к интернету.
- Временно отключите антивирус и Firewall.
java.net.SocketException: Connection reset / Удаленный хост принудительно разорвал существующее подключение
Ошибка сети «соединение сброшено». Как и в предыдущей ошибке, проблема связана с «плохим» интернетом, либо проблемами на стороне сервера (в этом случае ошибка будет у всех). Чаще всего возникает у пользователей мобильного интернета (USB-модем). От вас никаких действий предпринимать не требуется, кроме как найти «другой интернет» или использовать VPN для обхода фильтра сайтов.
java.lang.ClassCastException: XXX cannot be cast to YYY
Ошибка в логике программы: попытка привести объект к классу, экземпляром коего объект не является.
Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.
java.io.IOException: Server returned HTTP response code: 000 for URL
Проблема на стороне веб-сервера. Стандартная библиотека Java выбрасывает исключение, если веб-сервер выдаёт, например, страницу «404 Not Found».
Решение: Сообщите о проблеме владельцу веб-сервера, URL которого указан в тексте ошибки.
java.lang.UnsatisfiedLinkError: Can’t load library:
Не удалось загрузить нативную библиотеку (скорее всего, отсутствует файл по указанному пути).
Что можно сделать:
- Чаще всего ошибка возникает из-за отсутствия библиотек LWJGL. Почему их файлы пропадают, пока остаётся загадкой. Если пути вы видите «.redserver/natives/2.9.1/lwjgl.dll», значит надо удалить папку natives, находящуюся в .redserver, чтобы лаунчер их скачал заново.
Неактуально: С версии 3.2 лаунчер проверяет наличие всех файлов и автоматически, при необходимости, перекачивает их.
java.lang.RuntimeException: Unknown character in
Синтаксическая ошибка в конфигурационном файле мода.
Что можно сделать:
- Удалите указанный в ошибке файл. Мод создаст новый с настройками по умолчанию.
- Если вам сложно удалить файл, можно сделать сброс конфигов через лаунчер. Нажмите в лаунчере на многоточие на кнопке «Играть»; выберите в меню пункт «Очистка клиента»; установите флажок возле «Сбросить конфигурацию» и запустите очистку.
- Выполните проверку диска на наличие ошибок. Испорченные файлы могут быть признаком неисправности диска.
java.lang.NullPointerException (NPE)
Ошибка в логике программы: попытка вызвать нестатичный метод, обратиться к полю несуществующего объекта — null.
Решение: Сообщите о проблеме разработчику программы, приложив лог ошибки.
java.net.UnknownHostException
Ошибка сети: не удаётся определить IP-адрес доменного имени (в общем, проблемы с DNS).
Что можно сделать:
- Иногда ошибка может возникать, если вы не подключены к интернету, либо же произошёл разрыв интернет-соединения. Обычно исчезает сама через небольшой промежуток времени после возобновления соединения. Если ошибка не исчезла — может помочь перезагрузка компьютера (сбрасывает кеш DNS).
- Доступ к ресурсу заблокирован вашим провайдером. Сейчас данная проблема актуальна для украинских пользователей: используемый нами Яндекс.DNS заблокирован в этой стране. Читайте, как обойти блокировку DNS.
java.io.EOFException: Unexpected end of ZLIB input stream
Неожиданный конец файла. В данном случае — ZIP-архива. Возникает например, когда вы пытаетесь распаковать недокачанный архив.
java.net.SocketException: Address family not supported by protocol family: connect
Проблема возникает из-за неправильной настройки протокола IPv6. Если таковой не поддерживается вашим интернет-провайдером, его поддержку следует отключить.
java.lang.OutOfMemoryError
А вот это как раз «любимая» ошибка про нехватку ОЗУ. Не стоит сразу спешить выставлять память в лаунчере на максимум, потому что дальнейшие действия зависят от сообщения к ошибке:
- Unable to create new native thread / Metaspace — в вашей системе закончились ресурсы (ОЗУ). Решается только путём завершения всех лишних программ, либо апгрейдом ПК (больше ОЗУ — больше программ можно запустить). Не забывайте, что следует использовать 64-разрядную систему.
- Java heap space — нехватка размера heap области памяти. Увеличьте лимит памяти в настройках лаунчера.
|
Дубина Андрей 0 / 0 / 0 Регистрация: 23.12.2018 Сообщений: 10 |
||||||||||||
|
1 |
||||||||||||
Не могу подключиться к базе данных06.03.2019, 00:20. Показов 13964. Ответов 1 Метки postgresql (Все метки)
Не могу подключиться к бд на elephantsql.com
Ошибка
__________________ 0 |
|
2390 / 2216 / 564 Регистрация: 28.12.2010 Сообщений: 8,658 |
|
|
06.03.2019, 00:32 |
2 |
|
Caused by: java.net.SocketTimeoutException: connect timed out на том конце никого нет. По телнету попробуй, скорее всего тоже не выдет. PS. хз откуда ты урл этот взял. Там после регистрации дают отдельный урл вида <blabla>.db.elephantsql.com:5432/<blabla> 0 |
Автор оригинала: baeldung.
1. введение
В этом уроке мы узнаем причину UnknownHostException на примере. Мы также обсудим возможные способы предотвращения и обработки исключения.
2. Когда Возникает исключение?
UnknownHostException указывает, что IP – адрес имени хоста не может быть определен. Это может произойти из-за опечатки в имени хоста:
String hostname = "http://locaihost"; URL url = new URL(hostname); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.getResponseCode();
Приведенный выше код вызывает исключение UnknownHostException , поскольку неправильно написанный localhost не указывает ни на какие IP-адреса.
Еще одна возможная причина UnknownHostException это задержка распространения DNS или неправильная конфигурация DNS.
Для распространения новой записи DNS по всему Интернету может потребоваться до 48 часов.
3. Как Это предотвратить?
Предотвращение возникновения исключения в первую очередь лучше, чем последующая обработка. Несколько советов по предотвращению исключения:
- Дважды проверьте имя хоста: Убедитесь, что нет опечатки, и обрежьте все пробелы.
- Проверьте настройки DNS системы: Убедитесь, что DNS-сервер включен и доступен, и если имя хоста новое, дождитесь, пока DNS-сервер догонит вас.
4. Как с Этим справиться?
UnknownHostException расширяет IOException , которое является проверенным исключением . Как и любое другое проверенное исключение, мы должны либо выбросить его, либо окружить блоком try-catch .
Давайте рассмотрим исключение в нашем примере:
try {
con.getResponseCode();
} catch (UnknownHostException e) {
con.disconnect();
}
Рекомендуется закрывать соединение при возникновении UnknownHostException . Большое количество расточительных открытых соединений может привести к тому, что приложению не хватит памяти.
5. Заключение
В этой статье мы узнали, что вызывает UnknownHostException , как его предотвратить и как с ним справиться.
Как всегда, код доступен на Github .
-
Метки
exception, hostname, server, unknownhostexception
The UnknownHostException is an exception in Java that is thrown to indicate that the IP address of a host could not be determined.
Since the UnknownHostException is a checked exception, it either needs to be thrown or surrounded by a try-catch block in code.
What Causes UnknownHostException
The UnknownHostException occurs when trying to connect to a remote host using its hostname, but the IP address of the host could not be determined. This usually happens because of a typo in the hostname, or because of a DNS misconfiguration or propagation delay.
UnknownHostException Example
Here is an example of an UnknownHostException thrown when trying to connect to an unknown host:
public class UnknownHostExceptionExample {
public static void main(String[] args) {
String host = "https://rollbar.co";
URL url = null;
try {
url = new URL(host);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
System.out.println(con.getResponseCode());
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
The above code attempts to connect to a remote host, but has a typo in the hostname. Therefore, running the code throws an UnknownHostException exception:
java.net.UnknownHostException: rollbar.co
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:567)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:333)
at java.base/java.net.Socket.connect(Socket.java:648)
at java.base/sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:290)
at java.base/sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:173)
at java.base/sun.net.NetworkClient.doConnect(NetworkClient.java:182)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:474)
at java.base/sun.net.www.http.HttpClient.openServer(HttpClient.java:569)
at java.base/sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:265)
at java.base/sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:372)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:177)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1194)
at java.base/sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1082)
at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:163)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1600)
at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1528)
at java.base/java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:527)
at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:308)
at UnknownHostExceptionExample.main(UnknownHostExceptionExample.java:14)
How to Handle UnknownHostException
Since UnknownHostException is a checked exception, it can be handled by surrounding it with a try-catch block. The earlier example can be updated to handle the exception:
public class UnknownHostExceptionExample {
public static void main(String[] args) {
String host = "https://rollbar.co";
URL url = null;
HttpURLConnection con = null;
try {
url = new URL(host);
con = (HttpURLConnection) url.openConnection();
System.out.println(con.getResponseCode());
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (UnknownHostException uhe) {
uhe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
}
}
In the above example, the code that can throw the UnknownHostException is surrounded in a try-catch block. A finally block is also included to close the connection if the UnknownHostException occurs. This is good practice since too many open connections can cause the application to run out of memory.
How to Avoid UnknownHostException
The UnknownHostException can be avoided with the following checks:
- Valid hostname — The hostname should be double checked to make sure it does not contain any typos or whitespaces.
- DNS settings — The system DNS settings should be checked to ensure that the DNS server is reachable. If the hostname is new, it may take some time for the DNS server to catch up.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!


