import socket, sys

if len(sys.argv) !=3 :
print "Usage: ./supabot.py <host> <port>"
sys.exit(1)

irc = sys.argv[1]
port = int(sys.argv[2])
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send('JOIN #darkunderground' + '\r\n')
data = ''
while True:
      data = sck.recv(1024)
      if data.find('PING') != -1:
         sck.send('PONG ' + data.split() [1] + '\r\n')
         print data
      elif data.find('!info') != -1:
          sck.send('PRIVMSG #darkunderground supaBOT v1.0 by sourD' + '\r\n')


print sck.recv(1024)

when I run this code I get this error..

socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host

it says that the error is in line 16, in data = sck.recv(1024)

Bella's user avatar

Bella

3,20923 silver badges26 bronze badges

asked Jun 17, 2010 at 4:46

SourD's user avatar

You need to check the IRC protocol a little it more; your IRC session is not considered conncted (by the server) until certain actions have been completed which the server will inform your client about using IRC protocol codes. And if the server or network is busy when you are connecting it will take longer for these actions to complete.

In this case attempting to join a channel before the server has given you the MOTD (message of the day) would cause a disconnection by the server. The end of MOTD protocol code is 376 and indicates that the IRC connection sequence is over, and you can proceed with your IRC session eg: enter commands (like join).

I would suggest entering a RECV loop and monitoring data received from the server for the IRC code 376 before you attempt to join a channel, in Perl this would look somthing like this:

 sub chan_join{
  while(my $input = <SOCK>){
    if($input =~ /376/){
      my $talk = "JOIN $channel";
      &send_data($talk);
      &monitor;
    }
    else { print "$input";  }
  }
}

Pretty poor but you get the idea right? (please note its only necessary to check for 376 once, once seen you are connected and you only need to maintain the connection by responding to the server ‘PING’s)

answered Jun 20, 2010 at 16:34

Bella's user avatar

BellaBella

3,20923 silver badges26 bronze badges

That probably means that you’re not supplying the expected handshake or protocol exchange for the server, and it is closing the connection.

What happens if you telnet to the same machine and port and type in the same text?

answered Jun 17, 2010 at 4:49

John Weldon's user avatar

John WeldonJohn Weldon

39.9k11 gold badges94 silver badges127 bronze badges

2

The remote host is issuing a TCP reset (RST), after accepting the connection. This can happen for a lot of reasons, including:

  • Firewall rules
  • Remote application error
  • Remote application simply closes the connection
  • etc.

As John Weldon said, try telnetting to the same machine and port and entering the commands manually.

Also, a good wire sniffer (Ethereal, WireShark, etc.) is highly useful for diagnosing this kind of problem.

answered Jun 20, 2010 at 12:59

Brian Clapper's user avatar

Brian ClapperBrian Clapper

25.7k7 gold badges65 silver badges65 bronze badges

The “10054 Error” is a common error encountered by Python users when working with the socket programming module. It is a connection-reset error, which occurs when the connection between the client and the server is unexpectedly closed. This error can occur due to various reasons, such as network connectivity issues, unexpected termination of the server, or the server being unable to handle the requested workload. Solving the 10054 error requires identifying the root cause of the problem and implementing a solution that addresses it.

Method 1: Increasing the Timeout Value

To solve the 10054 error in Python, you can increase the timeout value. This can be done using the socket module in Python.

Here is an example code snippet that shows how to increase the timeout value:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.settimeout(10)

try:
    s.connect(('localhost', 8080))
except socket.timeout:
    print('Connection timed out')

In the above code, we first create a socket object using the socket module. We then set the timeout value to 10 seconds using the settimeout() method. This method takes a single argument, which is the timeout value in seconds.

We then attempt to connect to the server using the connect() method. If the connection times out, we catch the socket.timeout exception and print an error message.

It is important to note that increasing the timeout value may not always solve the 10054 error. This error can have many different causes, and it is important to diagnose the root cause before attempting any solutions.

In summary, to solve the 10054 error in Python using the “Increasing the Timeout Value” method, you can use the settimeout() method from the socket module to increase the timeout value.

Method 2: Handling exceptions

When working with network programming in Python, it is common to encounter socket errors such as the 10054 error. This error occurs when a connection is forcibly closed by the remote host. To handle this error, we can use Python’s built-in exception handling mechanism. Here’s an example:

import socket

HOST = 'localhost'
PORT = 8000

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    # do something with the connection
except socket.error as e:
    if e.errno == 10054:
        print("Connection reset by peer")
    else:
        print("Socket error:", e)
finally:
    s.close()

In the code above, we create a socket object and attempt to connect to a remote host. If an error occurs, we catch the exception and check if the error code is 10054. If it is, we print a message indicating that the connection was reset by the remote host. Otherwise, we print the error message. Finally, we close the socket.

Another way to handle the 10054 error is to set a timeout on the socket. Here’s an example:

import socket

HOST = 'localhost'
PORT = 8000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5) # set timeout to 5 seconds
try:
    s.connect((HOST, PORT))
    # do something with the connection
except socket.timeout:
    print("Connection timed out")
except socket.error as e:
    if e.errno == 10054:
        print("Connection reset by peer")
    else:
        print("Socket error:", e)
finally:
    s.close()

In the code above, we set a timeout of 5 seconds on the socket using the settimeout method. If the connection is not established within this time, a socket.timeout exception is raised. We catch this exception and print a message indicating that the connection timed out.

In conclusion, handling the 10054 error in Python can be done using exception handling and setting a timeout on the socket. By using these techniques, you can write more robust network programs that can handle errors gracefully.

Method 3: Debugging the Connection

When dealing with the 10054 error in Python, it’s important to debug the connection to identify the root cause of the problem. Here are the steps you can follow to debug the connection:

Step 1: Check the Connection

The first step is to check the connection to ensure that it’s established properly. You can use the connect_ex() method to check the connection. Here’s an example:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex(('localhost', 8080))

if result == 0:
    print("Connection established successfully")
else:
    print("Connection failed with error code %d" % result)

Step 2: Set Timeout

If the connection is established properly, the next step is to set a timeout for the connection. You can use the settimeout() method to set a timeout. Here’s an example:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)

try:
    s.connect(('localhost', 8080))
    print("Connection established successfully")
except socket.timeout:
    print("Connection timed out")
except socket.error as e:
    print("Connection failed with error %s" % e)

Step 3: Check for Data

If the connection is established and a timeout is set, the next step is to check for data. You can use the recv() method to check for data. Here’s an example:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)

try:
    s.connect(('localhost', 8080))
    print("Connection established successfully")
    
    # Check for data
    data = s.recv(1024)
    if data:
        print("Data received: %s" % data)
    else:
        print("No data received")
except socket.timeout:
    print("Connection timed out")
except socket.error as e:
    print("Connection failed with error %s" % e)

Step 4: Close the Connection

After checking for data, it’s important to close the connection properly. You can use the close() method to close the connection. Here’s an example:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)

try:
    s.connect(('localhost', 8080))
    print("Connection established successfully")
    
    # Check for data
    data = s.recv(1024)
    if data:
        print("Data received: %s" % data)
    else:
        print("No data received")
except socket.timeout:
    print("Connection timed out")
except socket.error as e:
    print("Connection failed with error %s" % e)
finally:
    # Close the connection
    s.close()

By following these steps, you can debug the connection and solve the 10054 error in Python.

Method 4: Updating the Network Drivers

If you are encountering the 10054 error in Python, updating your network drivers may help solve the problem. Here are the steps to follow:

  1. First, you need to determine the type of network adapter you have. You can do this by opening the Device Manager in Windows and navigating to the Network Adapters section.

  2. Once you have determined the type of network adapter, go to the manufacturer’s website and download the latest driver for your adapter.

  3. Install the new driver by following the manufacturer’s instructions. This may involve running an installer program or manually updating the driver through the Device Manager.

  4. After the new driver is installed, restart your computer to ensure that the changes take effect.

Here is an example code snippet that demonstrates how to update the network drivers for a Realtek PCIe GBE Family Controller:

import subprocess

adapter_name = "Realtek PCIe GBE Family Controller"

driver_path = subprocess.check_output(["wmic", "path", "win32_networkadapter", "where", f'"name=\'{adapter_name}\'"', "get", "driverfilename"]).decode("utf-8").split("\n")[1].strip()


subprocess.run(["driver.exe", "/S"])

subprocess.run(["shutdown", "/r", "/t", "0"])

In this example, we use the subprocess module to run command-line programs that interact with the system. We first get the name of the network adapter (Realtek PCIe GBE Family Controller) and then use the wmic command to get the path of the device driver. We then download the latest driver from the manufacturer’s website and save it to a file called driver.exe. Finally, we install the new driver and restart the computer to ensure that the changes take effect.

Hopefully, this example code helps you update your network drivers and solve the 10054 error in Python.

Method 5: Checking for Firewall Restrictions

If you are facing the 10054 error in Python, it may be due to firewall restrictions. Here is how you can check for firewall restrictions and solve the error.

Step 1: Check for Firewall Restrictions

To check for firewall restrictions, you can use the socket module in Python. Here is an example code:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("www.google.com", 80))
s.send(b"GET / HTTP/1.1\r\n\r\n")
response = s.recv(1024)
print(response)
s.close()

This code creates a socket connection to www.google.com on port 80 and sends a GET request. If the connection is successful, it will print the response.

If you are facing the 10054 error, it means that the connection is being reset by the remote host. This can happen due to firewall restrictions.

Step 2: Disable Firewall

To solve the 10054 error, you can try disabling the firewall temporarily and see if it resolves the issue. Here is an example code:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect(("www.google.com", 80))
s.send(b"GET / HTTP/1.1\r\n\r\n")
response = s.recv(1024)
print(response)
s.close()

In this code, we have added a timeout of 5 seconds to the socket connection using the settimeout() method. This will ensure that the connection is not blocked indefinitely due to firewall restrictions.

Step 3: Use a Proxy Server

If disabling the firewall does not solve the issue, you can try using a proxy server to establish the connection. Here is an example code:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect(("proxy.example.com", 8080))
s.send(b"CONNECT www.google.com:80 HTTP/1.1\r\n\r\n")
response = s.recv(1024)
print(response)
s.send(b"GET / HTTP/1.1\r\n\r\n")
response = s.recv(1024)
print(response)
s.close()

In this code, we are using a proxy server at proxy.example.com on port 8080 to establish the connection to www.google.com on port 80. We are sending a CONNECT request to the proxy server to establish the connection and then sending the GET request to the remote host.

By following these steps, you can check for firewall restrictions and solve the 10054 error in Python.

Posted on Aug. 24, 2023, 2:55 a.m. by Jennifer Mitchell

Category:
The back-end

Tag:
security

Python socket.error: [Errno 10054] The remote host forced an existing connection to close. Problem solution:

Read web pages using Python the other day. The use of urlopen on a site is considered an attack by that site. Sometimes downloads are no longer allowed. Request.read () remains stuck after urlopen(). Errno 10054 is thrown.

This error is Connection reset by peer. The legendary remote host resets the connection. The possible cause is that the socket timeout period is too long. Request = urllib.request.urlopen(url), request.close(); It could also be that the failure to sleep for a few seconds causes the site to identify the behavior as an attack.

The specific solution is as follows:

[python] view plain copy

  1. import socket  
  2. import time  
  3. timeout = 20    
  4. Socket.setdefaulttimeout (timeout)# set timeout for the entire socket layer. If the socket is used in subsequent files, you do not need to set it
  5. sleep_download_time = 10  
  6. Sleep (sleep_download_time) #
  7. Request = urllib.request.urlopen(url)# here is the url to read the content
  8. Content = request.read()#
  9. Request.close ()# Remember to close

Because the read() operation after urlopen actually calls some socket layer function. Therefore, by setting the default socket timeout period, the network can be disconnected by itself. You don’t have to wait forever at read().

You can also write a try,except, for example:

[python] view plain copy

  1. try:  
  2.     time.sleep(self.sleep_download_time)  
  3.     request = urllib.request.urlopen(url)  
  4.     content = request.read()  
  5.     request.close()  
  6.       
  7. except UnicodeDecodeError as e:  
  8.          
  9.     print(‘—–UnicodeDecodeError url:’,url)  
  10.       
  11. except urllib.error.URLError as e:  
  12.     print(“—–urlError url:”,url)  
  13.   
  14. except socket.timeout as e:  
  15.     print(“—–socket timout:”,url)  

Generally speaking, there is no problem. I tested thousands of web downloads before SAYING this. However, if I download thousands of files, AND I run a test, MS will still jump the exception. It could be that time.sleep() is too short, or the network is suddenly down. I tested it using urllib.request.retrieve() and found that there was always a failure as data was downloaded over and over again.

The easy way to do this is to first refer to my article: Simple Implementations of Python checkpoints. Make a checkpoint first. Then, while True the above part of the code will run the exception. See the pseudocode below:

[c-sharp] view plain copy

  1. def Download_auto(downloadlist,fun,sleep_time=15):  
  2.     while True:          
  3. Try: # outsource a layer try
  4. Value = fun(downloadlist,sleep_time) #
  5. Only normal execution can exit.
  6.             if value == Util.SUCCESS:  
  7.                 break  
  8. Except: # if 10054 or IOError or XXXError occurs
  9. Sleep_time += 5 # Sleep 5 seconds longer and retry the download above. Because of the checkpoint, the above program continues execution where the exception was thrown. Prevents program interruption due to unstable network connection.
  10.             print(‘enlarge sleep time:’,sleep_time)  

However, for the corresponding page can not be found, and to do another processing:

[c-sharp] view plain copy

  1. # Print download information
  2. def reporthook(blocks_read, block_size, total_size):  
  3.     if not blocks_read:  
  4.         print (‘Connection opened’)  
  5.     if total_size  0:  
  6.         print (‘Read %d blocks’ % blocks_read)  
  7.     else:  
  8. # If the page is not found, the page does not exist, maybe totalsize is 0
  9. Print (‘downloading:%d MB, totalsize:%d MB’ % (blocks_read*block_size/1048576.0,total_size/1048576.0))
  10.         
  11.   
  12. def Download(path,url):  
  13. # url = ‘downloads.sourceforge.net/sourceforge…
  14.     #filename = url.rsplit(“/”)[-1]  
  15.     try:  
  16. # Python’s built-in download function
  17.         urllib.request.urlretrieve(url, path, reporthook)  
  18. Except IOError as e:
  19.         print(“download “,url,”/nerror:”,e)  
  20.     print(“Done:%s/nCopy to:%s” %(url,path))  

If you still have problems… Please add other solutions in the comments.

CSDN Official study Recommendation ↓ ↓ ↓* * * *

CSDN provides a full stack knowledge graph for Python.

You may like:

Python socket.error: [Errno 10054] the remote host forced an existing connection to close. Solution to the problem:

The other day I used python to read web pages. Because of the heavy use of the urlopen operation on a site, it is considered an attack by that site. Sometimes downloads are no longer allowed. After causing urlopen(), requeste.read () remains stuck. Finally, errno 10054 is thrown.

The error is connection reset by peer. The reason may be socket timeout time is too long; It could also be that after request = urllib.request-urlopen (url), there is no request-close () operation. It could also be that there is no sleep for a few seconds, leading the site to conclude that this behavior is an attack.

The specific solution is as follows:


01.import socket 
02.import time 
03.timeout = 20  
04.socket.setdefaulttimeout(timeout)# Here for the whole socket The layer sets the timeout time. If used again in subsequent files socket , no need to set   
05.sleep_download_time = 10 
06.time.sleep(sleep_download_time) # Here the time is set by itself   
07.request = urllib.request.urlopen(url)# This is where the content is going to be read url  
08.content = request.read()# Read, usually an exception will be reported here   
09.request.close()# Remember to close it  

Because the read() operation after urlopen is actually calling some function of the socket layer. So set the socket default timeout time, you can let the network break itself. You don’t have to wait forever at read().

Of course, you can also write several try outside,except, for example:


try: 
  time.sleep(self.sleep_download_time) 
  request = urllib.request.urlopen(url) 
  content = request.read() 
  request.close() 
   
except UnicodeDecodeError as e: 
     
  print('-----UnicodeDecodeError url:',url) 
   
except urllib.error.URLError as e: 
  print("-----urlError url:",url) 
 
except socket.timeout as e: 
  print("-----socket timout:",url) 

Generally speaking, there is no problem. I tested thousands of web downloads before I said this. But if I downloaded thousands of them, and I tested them, ms would still jump out of this exception. It could be time. Sleep () is too short, or it could be a sudden network outage. I tested it with urllib.request-retrieve () and found that there were always failures as I kept downloading data.

The easy way to do this is to first refer to my article: (link: #). Do a checkpoint first. Then, while True the above bit of code that will run an exception. See the pseudocode below:


def Download_auto(downloadlist,fun,sleep_time=15): 
  while True:     
    try: #  A layer of outsourcing try  
      value = fun(downloadlist,sleep_time) #  Here, fun Is your download function, I pass in when the function pointer.  
      #  Only normal execution can exit.   
      if value == Util.SUCCESS: 
        break 
    except : #  If that happens 10054 or IOError or XXXError 
      sleep_time += 5 # More sleep 5 Second, re-execute the above download. Because of the checkpoint, the above program continues execution from where the exception was thrown. Prevents program interruption due to unstable network connection.  
      print('enlarge sleep time:',sleep_time) 

However, for the corresponding web page, and to do another processing:


#  Print download information   
def reporthook(blocks_read, block_size, total_size): 
  if not blocks_read: 
    print ('Connection opened') 
  if total_size < 0: 
    print ('Read %d blocks' % blocks_read) 
  else: 
    #  If you can't find it, the page doesn't exist, maybe totalsize is 0 Cannot calculate the percentage   
    print('downloading:%d MB, totalsize:%d MB' % (blocks_read*block_size/1048576.0,total_size/1048576.0)) 
    
 
def Download(path,url): 
#url = 'http://downloads.sourceforge.net/sourceforge/alliancep2p/Alliance-v1.0.6.jar' 
  #filename = url.rsplit("/")[-1]  
  try: 
  # python The built-in download function   
    urllib.request.urlretrieve(url, path, reporthook) 
  except IOError as e: #  If you can't find it, it's going to cause it IOError .  
    print("download ",url,"/nerror:",e) 
  print("Done:%s/nCopy to:%s" %(url,path)) 

If you still have a problem… Please note other solutions in the comments.

socket.error: [Errno 10054]

import socket, sys

if len(sys.argv) !=3 :
print "Usage: ./supabot.py <host> <port>"
sys.exit(1)

irc = sys.argv[1]
port = int(sys.argv[2])
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((irc, port))
sck.send('NICK supaBOT\r\n')
sck.send('USER supaBOT supaBOT supaBOT :supaBOT Script\r\n')
sck.send('JOIN #darkunderground' + '\r\n')
data = ''
while True:
      data = sck.recv(1024)
      if data.find('PING') != -1:
         sck.send('PONG ' + data.split() [1] + '\r\n')
         print data
      elif data.find('!info') != -1:
          sck.send('PRIVMSG #darkunderground supaBOT v1.0 by sourD' + '\r\n')


print sck.recv(1024)

когда я запускаю этот код, я получаю эту ошибку..

socket.error: [Errno 10054] Существующее соединение было принудительно закрыто удаленным хостом

пишет, что ошибка в строке 16, в data = sck.recv(1024)

person
SourD
  
schedule
17.06.2010
  
source
источник


Ответы (3)

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

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

Я бы предложил ввести цикл RECV и отслеживать данные, полученные с сервера, для кода IRC 376, прежде чем пытаться присоединиться к каналу, в Perl это будет выглядеть примерно так:

 sub chan_join{
  while(my $input = <SOCK>){
    if($input =~ /376/){
      my $talk = "JOIN $channel";
      &send_data($talk);
      &monitor;
    }
    else { print "$input";  }
  }
}

Довольно бедно, но вы правильно поняли идею? (обратите внимание, что необходимо проверить наличие 376 только один раз, как только вы увидите, что вы подключены, и вам нужно только поддерживать соединение, отвечая на «PING» сервера)

person
Bella
  
schedule
20.06.2010

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

Что произойдет, если вы подключитесь через telnet к тому же компьютеру и порту и наберете тот же текст?

person
John Weldon
  
schedule
17.06.2010

Удаленный хост выдает сброс TCP (RST) после принятия соединения. Это может произойти по многим причинам, в том числе:

  • Правила брандмауэра
  • Ошибка удаленного приложения
  • Удаленное приложение просто закрывает соединение
  • и т.п.

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

Кроме того, для диагностики такого рода проблем очень полезен хороший анализатор проводов (Ethereal, WireShark и т. д.).

person
Brian Clapper
  
schedule
20.06.2010

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *