Socket.error: Invalid Argument supplied - python

I am learning networking programming and trying to grasp the basics of sockets through this example.
import socket,sys
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
MAX = 65535
PORT = 1060
if sys.argv[1:] == ['server']:
s.bind(('127.0.0.1',PORT))
print 'Listening at ' , s.getsockname()
while True:
data,address = s.recvfrom(MAX)
print ' The address at ' , address , ' says ' , repr(data)
s.sendto('your data was %d bytes' % len(data),address)
elif sys.argv[1:] == ['client']:
print ' Address before sending ' ,s.getsockname()
s.sendto('This is the message',('127.0.0.1',PORT))
print ' Address after sending ' ,s.getsockname()
data,address = s.recvfrom(MAX)
print ' The server at ' , address , ' says ' , repr(data)
else:
print >> sys.stderr, 'usage: udp_local.py server | client '
However,its throwing up an exception saying the arguments given by getsockname() were invalid specifically on line 22.The code is correct as far as I know.Here's the exception
Traceback (most recent call last):
File "udp_local.py", line 23, in <module>
print ' Address before sending ' ,s.getsockname()
File "c:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10022] An invalid argument was supplied
Using PyScripter 2.5.3.0 x86

Well I got the problem.The socket doesn't have an address untill its either binded or data is sent.
Just had to comment it out.
elif sys.argv[1:] == ['client']:
## print ' Address before sending ' ,s.getsockname()
Thanks

Related

reading port number as an argument and do stuff

I wrote the following script in python:
#!/usr/bin/python
import socket
import sys
import os
host=sys.argv[1]
port=sys.argv[2]
if len(sys.argv) != 3:
print 'Usage: python %s <HostName> <PortNumber>' % (sys.argv[0])
sys.exit();
try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to creat socket. Error code: ' + str(msg[0]) + ' Error message: ' + msg[1]
sys.exit();
try:
host_ip=socket.gethostbyname(host)
except socket.gaierror:
print 'Host name could not be resolved. Exiting...'
sys.exit();
print 'IP address of ' + host + ' is ' + host_ip + ' .'
try:
s.connect((host_ip, port)) #OR s.connect((host_ip, sys.argv[2]))
except socket.error, (value,message):
if s:
s.close();
print 'Socket connection is not established!\t' + message
sys.exit(1);
print 'Socket connected to ' + host + 'on IP ' + host_ip + 'on port number ' + port + '.'
But when I run it this error occures:
s.connect((host_ip, port))
return getattr(self._sock,name)(*args)
TypeError: an integer is required
What is wrong here?
Thanks
The error message is the answer.
port shall be an integer and you are passing in str
before you call s.connect((host_ip, port)) do
port = int(port)
You should use argparse to process your arguments. It provides many useful features in addition to making it easy to fix your immediate problem (not making the port number an integer). Replace
host=sys.argv[1]
port=sys.argv[2]
if len(sys.argv) != 3:
print 'Usage: python %s <HostName> <PortNumber>' % (sys.argv[0])
sys.exit();
with
import argparse
p = argparse.ArgumentParser()
p.add_argument("host")
p.add_argument("port", type=int)
args = p.parse_args()
# And optionally
host = args.host
port = args.port
connect() requires an integer for the port argument, and since you accepted port as an argument it's a string. Make sure you typecast it as an int - s.connect((host_ip, int(port)).
The sys.argv list is a list of strings, so you should convert it to an integer with the build-in int() function:
port = int(sys.argv[2])

Line 29, in " <module> s.sendall(message)" TypeError: 'str' does not support the buffer interface [duplicate]

This question already has answers here:
TypeError: 'str' does not support the buffer interface
(7 answers)
Closed 8 years ago.
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print ('Failed to create socket')
sys.exit();
print ('Socket Created', s)
host = 'www.google.com'
port = 80
try:
remote_ip = socket.gethostbyname(host)
except socket.gaierror:
print ('Hostname could not be resolved. Exiting')
sys.exit()
print ('Ip address of "' + host + '" is: ' + remote_ip )
s.connect((remote_ip, port))
print ('Socket Connected to ' + host + ' on ip ' + remote_ip)
message = 'GET / HTTP/1.1\r\n\r\n'
try:
s.sendall(message)
except socket.error:
print ('Send Failed')
sys.exit()
print ('Message send successfully')
reply = s.recv(4096)
print ('reply')
In Python 3, str is a unicode string, which could have a wide variety of byte representations. Strings are unicode by default.
To get a plain byte string, you can prefix the string with b, such as b'GET / HTTP/1.1\r\n\r\n'. You can also use the encode method of a unicode string to get a specific encoding.
To learn more about Unicode, you should probably read the Python 3 Unicode HOWTO.

how to send a number from client to server

I can send messages in the form of strings but I cannot send integers to the server.
What I have done is this:
import socket #for sockets
import sys #for exit
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
sys.exit();
print 'Socket Created'
host = 'localhost'
port = 6000
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
print 'Ip address of ' + host + ' is ' + remote_ip
#Connect to remote server
s.connect((remote_ip , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
nb = input('Choose a number')
print ('Number%s \n' % (nb))
#Send some data to remote server
#message = nb
try :
#Set the whole string
s.send(mySocket, nb, sizeof(int),0);
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
you can use int() and str() function for convert integer to string and send it
and in other side with int() function convert it to integer
look at these links
http://docs.python.org/2/library/functions.html#int
http://docs.python.org/2/library/functions.html#str

What does this socket.gaierror mean?

I'm new to python and going through a book, Core Python Applications 3rd Edition. This is the the first example and already I'm stumped with it. Here's the code with the error at the end.
#!/usr/bin/env python
from socket import *
from time import ctime
HOST = ' '
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print 'waiting for connection...'
tcpCliSock, addr = tcpSerSock.accept()
print "...connected from:", addr
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send("[%s] %s" % (ctime(), data))
tcpCliSock.close()
tcpSerSock.close()
Traceback (most recent call last):
File "tsTserv.py", line 12, in <module>
tcpSerSock.bind(ADDR)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
What does this mean?
It means that your given host name ' ' is invalid (gai stands for getaddrinfo()).
As NPE already states, maybe an empty string '' would be more appropriate than a space ' '.
The
HOST = ' '
should read
HOST = ''
(i.e. no space between the quotes).
The reason you're getting the error is that ' ' is not a valid hostname. In this context, '' has a special meaning (it basically means "all local addresses").

Error when disconnecting from server

I keep getting this:
Traceback (most recent call last):
File "C:\Users\T_Mac\Desktop\Rex's Stuff\PyNet\Client.py", line 14, in <module
>
server.connect(ADDRESS)
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
File "C:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
When I run 'changeclient' with this code as my server:
# Server
from socket import *
PORT = 5000
BUFSIZE = 1024
ADDRESS = ('', PORT) # '' = all addresses.
server = socket(AF_INET, SOCK_STREAM)
server.bind(ADDRESS)
server.listen(5)
# print stuff the user needs to know
print ''
print ' ____ _____ ___ _______ '
print ' / \ | | / \ /____\ | '
print '| | | | | | | | '
print ' \____/ \____/| | | \____/ | v0.1'
print ' | | '
print ' | | '
print ' | | '
print ' | _____/ '
print 'Contact Rex for any bug reports at rexploits#gmail.com'
print '\n'
print 'Please input the command when prompted with \'>\''
print 'The stdout stuff will be in this format: '
print ' (<stdout>, <stderr>)\n'
while True:
END_SCRIPT = 0 #Setting command to something other than '1'
print '\nWaiting for connections...'
client, address = server.accept()
print '...client connected from ', address[0], '\n'
while True:
command = raw_input('> ')
if command == 'quit':
server.close()
END_SCRIPT = 1
break
elif command == 'exit':
server.close()
END_SCRIPT = 1
break
elif command == 'changeclient':
print 'Changing clients.....\n'
client.send(command)
break
else:
client.send(command)
commandJazz = client.recv(BUFSIZE)
print commandJazz
if END_SCRIPT == 1:
print 'Closing server......'
print 'Goodbye!'
break
server.close()
And this as my Client:
# client
from subprocess import *
from socket import *
import time
test = 0
PORT = 5000
IP = 'localhost' #To change it to your ip, delete 'raw_input('> ')' and put your IP in its place.
BUFSIZE = 1024
ADDRESS = (IP, PORT)
server = socket(AF_INET, SOCK_STREAM)
while True:
server.connect(ADDRESS)
while True:
command = server.recv(BUFSIZE)
if command == 'changeclient':
server.close()
test = 1
break
else:
executeIt = Popen(command, shell = True, stdin = PIPE, stdout = PIPE, stderr = STDOUT)
commandJazz = executeIt.communicate()
strCommandJazz = str(commandJazz)
server.send(strCommandJazz)
I run my server, then run two instances of my client. It connects fine and everything works fine. I have built in a command called changeclient to disconnect the current client and connect to another. Whenever I execute changeclient, I get the previously posted error on my client.
When you close your socket, dont reuse it. Create a new one:
server = socket(AF_INET, SOCK_STREAM)
server.connect(ADDRESS)
Right now you are trying to reconnect on the same socket instance.
You could also try to use a flag that tells the socket to reuse the port when you reopen it instead of creating a new one.
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

Categories

Resources