module 'socket' has no attribute 'getsockname' - python

This is a simple file server file using TCP sockets,
when i'm running this i'm getting the following error.
Can anyone tell me the solution to this
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = socket.getsockname() # Reserve a port for your service.
block_size = 1024 #file is divided into 1kb size
s.bind((host, port)) # Bind to the port
#f = open('paris.png','wb')
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
print("Receiving...")
l = c.recv(block_size)
while (l):
print("Receiving...")
l = c.recv(block_size)
#f.close()
print("Done Receiving")
mssg = 'Thank You For Connecting'
c.send(mssg.encode())
c.close() # Close the connection
Traceback (most recent call last):
File "C:\Users\Hp\Documents\Python codes\file_transfer_simple_server.py",line 5, in <module>
port = socket.getsockname() # Reserve a port for your service.
AttributeError: module 'socket' has no attribute 'getsockname'

As #Mark Tolonen mentioned in the comment, You were calling getsockname() on the socket module. getsockname is a method on the socket instance s
import socket
s = socket.socket()
s.bind(('localhost',12345))
host, port = s.getsockname() # unpack tuple
block_size = 1024
print(port)
# output
12345

Related

Instance of 'socket' has no 'gethostbyname' member Python3

Im coding a chat program with python. But when i write "host = socket.gethostname()" it gives me error. My file is named "server.py" (without quotes) How can i fix? Code:
import socket
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname()
port = 12347
socket.bind((host, port))
socket.listen(10)
c, addr = socket.accept()
c.sendall(bytes("Hi!".encode("utf-8")))
print("Connected to {}".format(addr))
while True:
data = str(c.recv(1024))[1:]
if data:
print("Client: {}".format(data))
respond = input("Server: ").encode("utf-8")
if respond == "q":
exit()
else:
c.sendall(bytes(respond.encode("utf-8")))
this should be a red flag:
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
when importing socket, socket is the socket module. The line above assigns the name socket to a socket object.
Then
host = socket.gethostbyname()
doesn't work because the method applies to the module, but the module name has been reassigned to the socket object.
That would work (renaming your socket object):
import socket
my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostbyname("localhost") # needs an argument, btw

Error: nodename nor servname provided, or not known (python sockets)

I am trying to learn how to use sockets using this tutorial:
https://www.tutorialspoint.com/python/python_networking.htm
I have copied the code from the site into my directory and ran it exactly as was done in the tutorial but got errors. Here is the code from the tutorial.
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print("asdf")
c.send('Thank you for connecting')
c.close() # Close the connection
and client.py
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
These are the console commands I ran:
python server.py &
python client.py
I got this errors after running the command:
Traceback (most recent call last):
File "client.py", line 9, in <module>
s.connect((host, port))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/soc ket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
In case this is helpful, the version of python I am using is Python 2.7.10 and I use a mac that is version 10.12.6
Thanks in advance
From the docs of socket.gethostname:
Return a string containing the hostname of the machine where the
Python interpreter is currently executing.
Note: gethostname() doesn’t always return the fully qualified domain
name; use getfqdn() for that.
The host IP is not the same as the hostname. You have a couple of options:
You can either manually assign host to 0.0.0.0 or localhost
You can also query socket.gethostbyname:
host = socket.gethostbyname(socket.gethostname()) # or socket.getfqdn() if the former doesn't work
I did some changes in your code. Here's the server.py
#!/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 = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5)
c,addr= s.accept()
print "Got connection from the ", addr
c.send('Thank you for connecting')
c.close() # Close the connection
Here's the client.py
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
msg = (s.recv(1024))
print msg
s.close # Close the socket when done
I hope it will help

Socket.error: [Errno 10022] An invalid argument was supplied

#!/usr/bin/env python
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('192.168.1.123', 5162))
clientsocket.send('getval.1')
clientsocket.close
clientsocket.bind(('192.168.1.124', 5163))
clientsocket.listen(1)
while True:
connection, address=clientsocket.accept()
value=connection.recv(1024)
print value
I'm trying to get python to send a message to the server, and in return the server responds. Yet when I execute this code it gives me
Socket.error: [Errno 10022] An invalid argument was supplied
It seems you wrote a mixed code of server and client
Here a simple sample of codes for socket programming the first on server side and the second on client
Server side code:
# server.py
import socket
import time
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
and now the client
# client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" % tm.decode('ascii'))
The server simply remained listened for any client and when it finds out a new connection it returns current datetime and closes the client connection

Getting an encoding error using sockets in Python

I have created two scripts which establish a client socket and server socket in localhost.
Server socket
import socket
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpsersoc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcpsersoc.bind(ADDR)
tcpsersoc.listen(5)
while True:
print('waiting for connection .... ')
print(ADDR)
tcpClisoc,addr = tcpsersoc.accept()
print('......connected from', addr)
while True:
data = tcpClisoc.recv(BUFSIZ)
if not data:
break
tcpClisoc.send('[%s]%s'%(bytes(ctime(),'UTF-8'),data))
tcpClisoc.close()
tcpsersoc.close()
Client socket
from socket import *
HOST= '127.0.0.1'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('>')
if not data:
break
tcpCliSock.send(data.encode('utf-8'))
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()
I'm still getting the below error despite converting the data into a bytes object. I'm using python 3.x
this is the error raised by the server socket
waiting for connection ....
('', 21567)
......connected from ('127.0.0.1', 52859)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
import exampletcpserver
File "C:/Python34\exampletcpserver.py", line 23, in <module>
tcpClisoc.send('[%s]%s'%(bytes(ctime(),'UTF-8'),data))
TypeError: 'str' does not support the buffer interface
Please let me know where i'm going wrong.
You are trying to send a string, but sockets require you to send bytes. Use
tcpClisoc.send(('[%s]%s' % (ctime(), data.decode("UTF-8"))).encode("UTF-8"))
Python 3.5 will support the alternative
tcpClisoc.send(b'[%s]%s' % (bytes(ctime(), 'UTF-8'), data))

Error - global name 'SOL_SOCKET is not defined

I am trying to create a basic instant message program that uses a p2p (peer-to-peer) connection so it will not need a server. I am pretty sure nothing is wrong, but every time I run the client program I have created, I get this error:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
NameError: global name 'SOL_SOCKET' is not defined
Here is the program:
import socket
def Receiver():
# Create socket that supports IPv4, TCP Protocol
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket created."
# Requests for IP of host (DNS)
dns = "localhost"
HOST = ''
PORT = 25395
try:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
except socket.error as serror:
print "socket error"
s.bind((HOST, PORT)) # Listens on all interfaces...
print 'Listening on port 25565'
s.listen(True) # Listen on the newly created socket...
conn, addr = s.accept()
print 'Connected in port 25565'
data = conn.recv(1024)
print data
s.close()
def Sender():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dns = "localhost"
HOST = socket.gethostbyname(dns)
port = 25565
# Connect to server
s.connect((host,port))
print "Socket connected to " + dns + " on IP " + host
# Assign message to be sent to server to a variable
message = raw_input("Message to be sent to server: ")
#Send the actual message to server
s.sendall(message)
print "Message sent successfully"
s.close()
input = raw_input('S is send, R is receive: ')
if input == 's':
Sender()
if input == 'r':
Receiver()
I have tried removing s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) but it tells me that I cannot use 2 sockets on the same port when there isn't 2 sockets using the same port.
In your code:
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
do like:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# ^^^^ added ^^^
because you imported just socket, check following code pieces:
>>> import socket
>>> SOL_SOCKET
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'SOL_SOCKET' is not defined
>>> socket.SOL_SOCKET
1

Categories