Python socket error - how to repair - python

I have this code:
>>> import socket
>>> sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sck.connect(('loaclhost', 2525))
And I have this error:
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
sck.connect(('localhost', 2526))
socket.error: [Errno 10061] No connection could be made because
the target machine actively refused it
Please helpe me. Where can be error? How can I repair it?

try changing the connection to "localhost" instead of "loaclhost"

Your code and error don't match (spelling of localhost and port number), but the error message is due to no server listening on that port. Cut and paste the exact code and error message next time.

Related

Why binding 0 port produces "Address already in use"?

I have this code:
socks = []
for i in range(20):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(False)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', 0))
socks.append(s)
# ...... Some code triggering s.connect_ex to calculate connection time ......
for s in socks:
s.shutdown(socket.SHUT_RDWR)
s.close()
Sometimes this code produces the following exception:
2022-07-04 16:06:59,147 ERROR - Thread 'Thread-239' failed
Traceback (most recent call last):
File "/root/connection_time/lib/time_socks.py", line 279, in time_socks
s.bind(('0.0.0.0', 0))
OSError: [Errno 98] Address already in use
Ps. The code in running as a root user.

Receive data from a client/server doesn't work

I developed a small Python program which should receive and output data from another client or server. However, I get an error message which is unknown to me. Can anyone help me? Thanks a lot
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.1.34', 80))
from_server = client.recv(4096)
client.close()
print from_server
Error:
Traceback (most recent call last):
File "CallManager2.py", line 4, in <module>
client.connect(('192.168.1.34', 80))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
The error comes from inability for your program to reach the server or other client.
Check that there is something listening to incoming connexions on the address you want to connect to.
Then you can check that the address you want to connect to is on the same network as your program.

server.bind(), only local ip address

I can't define a server with the real IP address of my computer, it gives me an error.When I do this with my local IP address it works but I want to run the client in other computer
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('my_ip',9876))
server_socket.listen(1)
(client_socket,client_address)=server_socket.accept()
recived_data=client_socket.recv(999999999)
password=open(r'D:\passwords','wb')
password.write(recived_data)
client_socket.close()
server_socket.close()
the client:
import socket
my_socket = socket.socket()
my_socket.connect(('the_real_ip', 9876))
the error I get is:
Traceback (most recent call last):
File "D:/Heights/Documents/Projects/Cyber/Password_Server.py", line 4, in <module>
server_socket.bind(('my_ip',9876))
File "D:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context
You can use server_socket.bind(('0.0.0.0',9876)) and server_socket.bind(('',9876))
Check this link: https://serverfault.com/questions/78048/whats-the-difference-between-ip-address-0-0-0-0-and-127-0-0-1
To connect from outside your LAN, you have to connect to the router of that LAN using the 'outside IP' and make let the router formward the connection to the 'local IP'.

AttributeError from client sockets in python

I'm getting an attribute error from running the client side of the program, I'm pretty sure I did it everything correctly but apparently not.
Here's the code:
from socket import *
serverName = 'hostname'
serverPort = 12000
clientSocket = socket(socket.AF_INET, socket.SOCK_DGRAM)
message = raw_input('Input lowercase sentence:')
clientSocket.sendto(message,(serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print modifiedMessage
clientSocket.close()
This is the error I get:
Traceback (most recent call last):
File "UDPClient.py", line 4, in <module>
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
AttributeError: type object '_socketobject' has no attribute 'socket'
EDIT:
Traceback (most recent call last):
File "UDPClient.py", line 6, in <module>
clientSocket.sendto(message,(serverName,serverPort))
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
You're getting this wrong. Since you import *, just use AF_INET and SOCK_DGRAM
>>> from socket import *
>>> clientSocket = socket(AF_INET, SOCK_DGRAM)
Tested on my machine using Py3.4

How to close socket after python fail?

First, I encountered sockets in Python and faced this problem: when some error in my python code occurs, for example some syntax error before conn.close() on the second script start port is in use. The script already finished, but the socket is still open, kind of like busy socket.
Here is an error just for example:
web#web-X501A1 /var/www $ cd /home/web/www/public/py
web#web-X501A1 ~/www/public/py $ python sockets.py
connected: ('127.0.0.1', 47168)
Traceback (most recent call last):
File "sockets.py", line 164, in <module>
data = re.find('(<onvif>.*<\/onvif>)')
AttributeError: 'module' object has no attribute 'find'
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
Code:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
try:
print 'connected:', addr
buffer = ''
while True:
buffer += conn.recv(1024)
data = re.find('(<code>.*<\/code>)', buffer)
print data
exit();
if not data:
continue
conn.send(data.upper())
except Exception:
pass
finally:
conn.close()
Enclose the usage of the socket in a try/finally clause. Close the socket in the finally part. Perhaps handle the exception in an except part. Something similar to this:
try:
result = x / y
except ZeroDivisionError:
print "division by zero!"
else:
print "result is", result
finally:
print "executing finally clause"
The problem here is the dirty socket closing which occurs when the script crashes without the proper TCP connection shutdown sequence. Thankfully there's a simple solution which tells the kernel to ignore the fact the socket is already in use (the port it's bound to):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
That's all, add that before the bind call and you're set. Debugging your other errors will be much simpler and less time consuming once that's done ;) See more in the docs https://docs.python.org/2/library/socket.html#socket.socket.setsockopt
If you use netstat -nutap you should notice that you connection seems like it's still up, on a state named TIME_WAIT.
That's part of TCP protocol, and according to wikipedia:
represents waiting for enough time to pass to be sure the remote TCP
received the acknowledgment of its connection termination request.
[According to RFC 793 a connection can stay in TIME-WAIT for a maximum
of four minutes known as a MSL (maximum segment lifetime).]
So, when you try to reconnect immediately to the same port, python complains that this port is still busy and cant be bound yet, saying:
socket.error: [Errno 98] Address already in use
See this old question, where it is asked how to avoid this waiting time.

Categories