Ответ несовсем по вопросу ябы сказал по реализации моего совета.
Мой пример реализации клиента и сервера на СИ .
Сервер
/* определяет типы данных */
#include <sys/types.h>
/* "Главный" по сокетам */
#include <sys/socket.h>
/* sockaddr_in struct, sin_family, sin_port, in_addr_t, in_port_t, ...*/
#include <netinet/in.h>
#include <stdio.h>
#include <memory.h>
#include <string.h>
#include <errno.h>
/**@brief Получает от клиента последовательность байт, не длиннее 30 и печатает её на экран по
* завершении соединения. Клиенту отправляет "Hi, dear!"*/
int main(int argc, char * argv)
{
/*создаём сокет*/
int s = socket(AF_INET, SOCK_STREAM, 0);
if(s < 0)
{
perror("Error calling socket");
return 0;
}
/*определяем прослушиваемый порт и адрес*/
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(18666);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if( bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0 )
{
perror("Error calling bind");
return 0;
}
/*помечаем сокет, как пассивный - он будет слушать порт*/
if( listen(s, 5) )
{
perror("Error calling listen");
return 0;
}
/*начинаем слушать, для соединения создаём другой сокет, в котором можем общаться.*/
int s1 = accept(s, NULL, NULL);
if( s1 < 0 )
{
perror("Error calling accept");
return 0;
}
/*читаем данные из сокета*/
char buffer[31];
int counter = 0;
for(;;)
{
memset(buffer, 0, sizeof(char)*31);
/*следует помнить, что данные поступают неравномерно*/
int rc = recv(s1, buffer, 30, 0);
if( rc < 0 )
{
/*чтение может быть прервано системным вызовом, это нормально*/
if( errno == EINTR )
continue;
perror("Can't receive data.");
return 0;
}
if( rc == 0 )
break;
printf("%sn", buffer);
}
char response[] = "Hi, dear!";
if( sendto( s1, response, sizeof(response), 0, (struct sockaddr *)&addr, sizeof(addr) ) < 0 )
perror("Error sending response");
printf("Response sendn");
return 0;
}
Клиент
include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
/* hton, ntoh и проч. */
#include <arpa/inet.h>
#include <memory.h>
#include <stdio.h>
int main(int argc, char * argv[])
{
/*объявляем сокет*/
int s = socket( AF_INET, SOCK_STREAM, 0 );
if(s < 0)
{
perror( "Error calling socket" );
return 0;
}
/*соединяемся по определённому порту с хостом*/
struct sockaddr_in peer;
peer.sin_family = AF_INET;
peer.sin_port = htons( 18666 );
peer.sin_addr.s_addr = inet_addr( "172.16.8.169" ); // тут замени на свой адрес адрес можно узнать командой sudo ifconfig
int result = connect( s, ( struct sockaddr * )&peer, sizeof( peer ) );
if( result )
{
perror( "Error calling connect" );
return 0;
}
/*посылаем данные
*
* Если быть точным, данные не посланы, а записаны где-то в стеке, когда и как они будут
* отправлены реализации стека TCP/IP виднее. Зато мы сразу получаем управление, не
* дожидаясь у моря погоды.*/
char buf[] = "Hello, world!";
result = send( s, "Hello, world!", 13, 0);
if( result <= 0 )
{
perror( "Error calling send" );
return 0;
}
/* закрываем соединения для посылки данных */
if( shutdown(s, 1) < 0)
{
perror("Error calling shutdown");
return 0;
}
/* читаем ответ сервера */
fd_set readmask;
fd_set allreads;
FD_ZERO( &allreads );
FD_SET( 0, &allreads );
FD_SET( s, &allreads );
for(;;)
{
readmask = allreads;
if( select(s + 1, &readmask, NULL, NULL, NULL ) <= 0 )
{
perror("Error calling select");
return 0;
}
if( FD_ISSET( s, &readmask ) )
{
char buffer[20];
memset(buffer, 0, 20*sizeof(char));
int result = recv( s, buffer, sizeof(buffer) - 1, 0 );
if( result < 0 )
{
perror("Error calling recv");
return 0;
}
if( result == 0 )
{
perror("Server disconnected");
return 0;
}
if(strncmp(buffer, "Hi, dear!", 9) == 0)
printf("Got answer. Success.n");
else
perror("Wrong answer!");
}
if( FD_ISSET( 0, &readmask ) )
{
printf( "No server response" );
return 0;
}
}
return 0;
}
Собираем сервер и запускаем его
dima@komp:~/mita/TCP_IP$ gcc client.c -o client
dima@komp:~/mita/TCP_IP$ ./client
В создаём отдельный терминал и там собираем клиент :
dima@komp:~/mita/TCP_IP$ gcc client.c -o client
dima@komp:~/mita/TCP_IP$ ./client
Сервер выведет
Hello, world!
Response send
Клиент выведет
Got answer. Success.
Server disconnected: Success
I want to setup an Apache Spark Cluster but I am not able to communicate from the worker machine to the master machine at port 7077 (where the Spark Master is running).
So I tried to telnet
to the master from the worker machine and this is what I am seeing:
root@worker:~# telnet spark 7077
Trying 10.xx.xx.xx...
Connected to spark.
Escape character is '^]'.
Connection closed by foreign host.
The command terminated with «Connection closed by foreign host» immediately. It does not timeout or anything.
I verified that the the host is listening on the port and since telnet
output shows «Connected to spark.» — this also means that the connection is successful.
What could be the reason for such behavior?
I am wondering if this closing of the connection could be the reason why I am not able to communicate from my worker machine to the master.
Anthon
77.8k42 gold badges164 silver badges221 bronze badges
asked Jul 1, 2015 at 17:23
2
The process that is listening for connections on port 7077 is accepting the connection and then immediately closing the connection. The problem lies somewhere in that application’s code or configuration, not in the system itself.
answered Jul 1, 2015 at 18:16
JohnJohn
16.4k1 gold badge33 silver badges42 bronze badges
2
I just learned of an odd behaviour in some virtual servers, especially those that are run NAT. You connect to the port exposed by the virtual server to the outside; the server then tries to forward the connection to a target; the target refuses. So the NAT will close your connection with no message whatsoever. Pull your hair out trying to figure out what’s going on. This is very much like the previous answer; the source is the interaction in the virtual host itself.
The most likely cause is that someone is using the port, and the application running only accepts one connection at a time, and refuses any additional connections.
answered Apr 11, 2016 at 1:54
1
The application has policy restrictions to connect only from localhost. Same «problem» with elasticsearch. You can check your app-config or you can make a tunnel. Do
ssh -N -L 7077:127.0.0.1:7077 userxy@spark
then on your machine:
telnet 127.0.0.1 7077
Philippos
12.9k2 gold badges37 silver badges76 bronze badges
answered May 19, 2017 at 8:52
We came across this very error when trying to debug why email (through Python code) sending from a host was failing. It turned out to be due to the mail queue on the mail server being full for this particular host.
answered Dec 5, 2016 at 12:34
pdppdp
6977 silver badges8 bronze badges
0
2
Сканирую сеть на наличие открытых портов. Нахожу порт, пробую соединиться к ip через открытый порт, появляется
telnet 46.158.5.204 4899
Trying 46.158.5.204…
Connected to 46.158.5.204.
Escape character is ‘^]’.
Connection closed by foreign host.
Такое всегда, со всеми айпи, со всеми портами. Бывает после надписи коннектед терминал просто встает и ни на что не реагирует.Пробывал также и к локальному пк, итог тот же. В чем вообще может быть проблема?
- Ссылка
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.
I try to connect to localhost with telnet:
% telnet localhost 6311
This connection succeed, but when I connect by external IP of my computer, connection fails:
% telnet x.x.x.x 6311
Trying x.x.x.x...
Connected to x.x.x.x
Escape character is '^]'.
Connection closed by foreign host.
What could be wrong?
asked May 5, 2013 at 13:28
3
The problem was with the service ( that was running on 6311)
The servise just was not configured to work with remote access.
It means, telnet was OK
answered May 5, 2013 at 18:52
sunnysunny
1851 gold badge1 silver badge9 bronze badges
Check what IP server is listening to. I am suspecting that your server is listening to localhost
or 127.0.0.1
. Make it listen to 0.0.0.0
(probably via some conf file).
You can verify it by running
netstat -tapnl | grep 6311
Check if it shows 127.0.0.1:6311
or 0.0.0.0:6311
answered May 5, 2013 at 14:48
anishsaneanishsane
9051 gold badge8 silver badges18 bronze badges
1
first you need to see the ubuntu system log with this command
sudo gedit /var/log/syslog
and if you will see this error «execv( /usr/sbin/tcpd ) failed: No such file or directory» then run this command
sudo apt-get install tcpd
it will solve your problem (if not then you need to search your system error on google)
answered May 21, 2020 at 13:58
Given only the informational message from telnet, most likely, the application that accepted your tcp connection either closed the connection on it’s own accord or the application crashed/died.
The reason is that all «Connection closed by foreign host.» by itself indicates is that the telnet application is of the opinion that the connection was shut down cleanly and the remote end initiated the shutdown. (And the OS/IP-stack (at least on my linux) will do a tcp-teardown if the application suddenly disappears, kill -9). To find out exactly why, your best bet would be if the application that listens to the port you telneted to logs somewhere and looking there for clues.
If this were to be network related you’d be far more likely to see something along the lines of timeout (or nothing happening at all) or connection reset by peer. If this somehow were caused by something along the network, that something would have to sort-of hijack your tcp-session to do the teardown handshake.