socket.accept() invalid argument - python

I was trying to create an easy client/server program with the module socket. it is the basic tutorial for every standard socket implementation.
#Some Error in sock.accept (line 13) --> no fix yet
import socket
import sys
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print >>sys.stderr, 'starting up on %s' % host
serversocket.bind((host, 9999))
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#listening for incoming connections
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection , client_address = serversocket.accept()
try:
print >>sys.stderr, 'connection from', client_address
#Receive data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr,'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall(data)
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
#Clean up the connection
#Will be executed everytime
connection.close()
The output it gives is
C:\Python27\python27.exe C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py
starting up on Marcel-HP
waiting for a connection
Traceback (most recent call last):
File "C:/Users/Marcel/Desktop/Projekte/Python/Sockets/Socket_Test/server.py", line 16, in <module>
connection , client_address = serversocket.accept()
File "C:\Python27\lib\socket.py", line 206, in accept
sock, addr = self._sock.accept()
socket.error: [Errno 10022] Ein ung�ltiges Argument wurde angegeben

Before accepting any connections, you should start to [listen()][1] to new connections.
Here is the basic example from python documentation :
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creation of the socket
s.bind((HOST, PORT)) # We tell OS on which address/port we will listen
s.listen(1) # We ask OS to start listening on this port, with the number of pending/waiting connection you'll allow
conn, addr = s.accept() # Then, accept a new connection
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
So, in your case, you only miss a serversocket.listen(1)right after the or serversocket.setsockopt(...)

Related

AWS Socket connection over internet using Python

This the server code using sockets. I have deployed in the AWS server. I am trying to access it from local machine which is outside AWS. I have opened the TCP port 10000 in the security group (custom TCP) to my local IP. But getting a error as shown below.
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall(data)
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
This is the client code (trial-sockets.py) i am using. The error i am getting is given below
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print(sys.stderr, 'connecting to %s port %s' % server_address)
sock.connect(server_address)
try:
# Send data
message = 'This is the message. It will be repeated.'
print(sys.stderr, 'sending "%s"' % message)
sock.sendall(message)
# Look for the response
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = sock.recv(16)
amount_received += len(data)
print >>sys.stderr, 'received "%s"' % data
finally:
print >>sys.stderr, 'closing socket'
sock.close()
Error Message:
arunachalam#LV-SL306:~/Documents/aws$ python3 trail-sockets.py
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'> connecting to localhost port 10000
Traceback (most recent call last):
File "trail-sockets.py", line 10, in <module>
sock.connect(server_address)
ConnectionRefusedError: [Errno 111] Connection refused

How to Send a file with keeping its extension through a python socket?

I'm trying to send one file which is txt file through a python socket. I want the txt file which is received by the client keeps its extension which is txt.
Here is my server's side:
import socket
port = 50000
s = socket.socket()
host = "localhost"
s.bind((host, port))
s.listen(5)
print 'Server listening....'
while True:
conn, addr = s.accept()
print 'Got connection from', addr
data = conn.recv(1024)
print('Server received', repr(data))
filename='file.txt'
f = open(filename,'rb')
while (f):
conn.send(filename)
f.close()
print('Done sending')
conn.close()
Here is my client's side:
import socket # Import socket module
s = socket.socket() # Create a socket object
host = "localhost" #Ip address that the TCPServer is there
port = 50000 # Reserve a port for your service every new transfer wants a new port or you must wait.
s.connect((host, port))
s.send("Hello server!")
while True:
print('receiving the file...')
data = s.recv()
if not data:
break
print('Successfully get the file')
s.close()
print('connection closed')
All I found online is either modifying this file or sending a text in that file.

How to stay connected to a single specified client

I have the below code and it receives the data I want, how I want, then terminates. How can I set this to connect to my client that always has the same IP and remain connected or listening from that client?
Its a barcode scanner and sends the data fine i just need to be always listing for it.
Servercode.py
import socket #for sockets
import sys #for exit
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM,)
except socket.error as err_msg:
print ('Unable to instantiate socket. Error code: ' + str(err_msg[0]) + ' , Error message : ' + err_msg[1])
sys.exit();
print ('Socket Initialized')
host = socket.gethostname()
port = 12345
s.bind((host, port))
s.listen(5)
print ('listening....')
conn, addr = s.accept()
print ('Got connection from', addr)
while 1:
data = conn.recv(1024)
stringdata = data.decode('ascii')
if not data: break
print ('received data:', stringdata)
conn.close()
You want to reject connections from IP addresses other than a specific one.
You already have most of what you need:
print ('Got connection from', addr)
Just add something like this:
if addr[0] != '192.168.1.200':
conn.close()

How to close a connection of a client when multiple clients are connected?

I am having a multi-client server which listens to multiple clients. Now if to one server 5 clients are connected and I want to close the connection between the server and just one client then how am I going to do that.
My server code is:
import socket
import sys
from thread import *
try:
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,msg:
print "Socket Creation Error"
sys.exit();
print 'Socket Created'
host = ''
port = 65532
try:
s.bind((host, port))
except socket.error,msg:
print "Bind Failed";
sys.exit()
print "Socket bind complete"
s.listen(10)
print "Socket now listening"
def clientthread(conn):
i=0
while True:
data = conn.recv(1024)
reply = 'OK...' + data
conn.send(reply)
print data
while True:
conn, addr = s.accept()
start_new_thread(clientthread,(conn,))
conn.close()
s.close()

How to use client socket as a server socket python

I like to have one port that first use for connect to another server and after that this port use to be a server and another clients connect to it.
I used python socket for client now I want to use it for server socket.
my code :
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12349
portt = 12341 # Reserve a port for your service.
s.bind((host, portt)) # Bind to the port
s.connect((host, port))
s.listen(5) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
print c
print 'Got connection from', addr
print s.recv(1024)
s.close
and the output is
Traceback (most recent call last):
File "client.py", line 12, in <module>
s.listen(5) # Now wait for client connection.
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument
How can I do that.
thank you for your answers!
Not sure what you are trying to do here. Seems to me that you are mixing client and server code in the same app.
For reference, you can create a simple echo server like this:
import socket
HOST = ''
PORT = 12349
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
And a simple echo client like this:
import socket
HOST = 'localhost'
PORT = 12349
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

Categories

Resources