What does this socket.gaierror mean? - python

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").

Related

how can i fix addr is not defined in python

I want to make a app like traceroute. I am trying to find routers IP adresses which i passed until i reach the machine and save them in my rota file. But i am taking addr is not defined error. I searched , usually they are giving addr = None but this is causing -'NoneType' object is not subscriptable- error. How can i fix it ?
This is my code:
import sys
import socket
dst = sys.argv[1]
dst_ip = socket.gethostbyname(dst)
f = open("rota.txt","w")
timeout = 0.2
max_hops = 30
ttl=1
port = 11111
while True:
receiver = socket.socket(family=socket.AF_INET,type=socket.SOCK_RAW,proto=socket.IPPROTO_ICMP)
receiver.settimeout(timeout)
receiver.bind(('',port))
sender = socket.socket(family=socket.AF_INET,type=socket.SOCK_DGRAM,proto=socket.IPPROTO_UDP)
sender.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
sender.sendto(b'',(dst_ip,port))
try:
data, addr = receiver.recvfrom(512)
f.write('\n' + str(addr[0]))
except socket.error:
pass
finally:
receiver.close()
sender.close()
ttl += 1
if ttl > max_hops or addr[0] == dst_ip:
break
And my errors:
Traceback (most recent call last):
File "rota.py", line 33, in <module>
if ttl > max_hops or addr[0] == dst_ip:
NameError: name 'addr' is not defined

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

Socket.error: Invalid Argument supplied

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

Categories

Resources