To practice network programming I am trying to set up a client and server, the client can send a message to the server. However, when trying to get input from user on client, it gets a NameError. I looked this error up and saw it used to pop up before python 3, instead of raw_input. However, I am using python 3.7.6 so I don't understand what could be wrong. Any help is appreciated!
Client code:
import socket
SERVER = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
SIZE = 1024
DISCONNECT_MESSAGE = "DISCONNECT"
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
client.send(message)
print(client.recv(SIZE).decode(FORMAT))
text = input("Type your message:")
send(text)
send(DISCONNECT_MESSAGE)
Traceback:
Traceback (most recent call last):
File "client.py", line 18, in <module>
text = input("(To disconnect type: 'DISCONNECT')\nType your message:")
File "<string>", line 1, in <module>
NameError: name 'hoi' is not defined
Related
Hello everyone, I am implementing a bittorrent client and i have hit a roadblock.
Here is my code to get the peer list from a particular tracker which only deals in ipv6.
tracker = "udp://tracker.birkenwald.de:6969/announce"
parse = urlparse(tracker)
ip, port = (socket.getaddrinfo(parse.hostname, parse.port, 0, 0, socket.SOL_TCP))[0][4][0], parse.port
#ip, port = 2001:1b10:1000:8101:0:242:ac11:2,6969
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.sendto(tracker_connection.bytestringForConnecting(), (ip, port))
#bytestringForConnecting() is a function for getting the byte version as written in the protocol.
Getting the following error
Traceback (most recent call last):
File "main.py", line 17, in <module>
t.get_peer_list()
File "/home/aditya/Desktop/CN/CN PROJECT/tracker.py", line 21, in get_peer_list
self.udp_request(url)
File "/home/aditya/Desktop/CN/CN PROJECT/tracker.py", line 64, in udp_request
sock.sendto(tracker_connection.bytestringForConnecting(), (ip, port))
socket.gaierror: [Errno -9] Address family for hostname not supported
The python socket documentation says that AF_INET6 addresses must be passed as a tuple of 4 values. If you pass a 2-tuple it'll be interpreted as AF_INET (IPv4) address.
import socket
PORT = 5050
SERVER = "Insert my public IPV4 address here"
ADDR = (SERVER, PORT)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR) #here is the line I get the error for
The error says:
Traceback (most recent call last):
File "The Directory", line 15, in <module>
server.bind(ADDR)
OSError: [WinError 10049] The requested address is not valid in its context
Can I not use my IPV4 to make the server public?
If not then what do I use?
I've written a python script that will communicate with a server, get its data and will send the data back to the server, some sort of an "echo client".
This is what I've written:
import socket
import time
def netcat(hostname, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.shutdown(socket.SHUT_WR)
while 1:
data = s.recv(1024)
if data == "":
break
print "Received:", repr(data)
data = data.replace("\n", "")
time.sleep(1)
s.sendall(data)
print "Sent:", data
print "Connection closed."
s.close()
netcat("127.0.0.1", 4444)
I get this output:
Received: 'Welcome!\n'
And after that, I get this error:
Traceback (most recent call last):
File "client.py", line 22, in <module>
netcat("127.0.0.1", 4444)
File "client.py", line 17, in netcat
s.sendall(data)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 32] Broken pipe
I've looked already for a solution for this error online, but with no luck.
Can someone please help me figure it out?
Thank you
I've been working on sockets a lot lately. I don't have a server right now to test your code so I thought I would quickly comment on what I see. You seem to be shutting down the socket (for writing) at the beginning, so your receive statement worked, but your sendall statement fails.
def netcat(hostname, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, port))
s.shutdown(socket.SHUT_WR) <-- WHY IS THIS HERE?
I am trying to connect and send data from my laptop to my Android phone via Bluetooth. I am using PyBluez library for that. When I am trying to call 'connect' method of BluetoothSocket:
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))
it always gives me the same error:
Traceback (most recent call last):
File "rfcomm-client.py", line 41, in <module>
sock.connect((host, port))
File "<string>", line 5, in connect
bluetooth.btcommon.BluetoothError: (22, 'Invalid argument')
As I understood from docs and examples, the type of host should be String, and port should be int. That I checked.
I also checked the validity of both port and host, and already paired my devices.
Could anybody help me with this issue?
The following code runs a socket server on a thread. The client socket sends 'client: hello' to the server, and the server socket receives and replies 'server: world'.
import socket
import threading
def server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('127.0.0.1', 12345))
sock.listen(1)
req, addr = sock.accept()
print req.recv(1024)
req.sendall('server: world')
def client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 12345))
sock.sendall('client: hello')
print sock.recv(1024)
def main():
t = threading.Thread(target=server)
t.start()
client()
if __name__ == '__main__':
main()
It runs ok as expected the first time, but from the second time, if you do not wait for a good few seconds for the server to release the socket, and if you try this on a Linux machine or Mac (Windows do not get it somehow) you will run into this error:
Traceback (most recent call last):
File "socket_send_receive.py", line 24, in <module>
main()
File "socket_send_receive.py", line 21, in main
client()
File "socket_send_receive.py", line 14, in client
sock.connect(('127.0.0.1', 12345))
File "<string>", line 1, in connect
socket.error: [Errno 111] Connection refused
Exception in thread Thread-1:
Traceback (most recent call last):
File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 532, in __bootstrap_inner
self.run()
File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 484, in run
self.__target(*self.__args, **self.__kwargs)
File "socket_send_receive.py", line 6, in server
sock.bind(('127.0.0.1', 12345))
File "<string>", line 1, in bind
error: [Errno 98] Address already in use
I am looking for some insight into why this is happening and if it is possible to be genuinely resolved or what best practice should be adopted.
I know already using this option can be a workaround thanks to the other posts here on stackoverflow.
socket.SO_REUSEADDR
When a socket is closed, it ends up in a state called STATE_WAIT (see this diagram). While the socket is in this state, no one else can use the same address (ip-number/port pair) unless the SO_REUSEADDR option is set on the socket.
See e.g. the Wikipedia article on TCP for more information about how TCP works and the different states.