I have some app that use UDP socket. Each app can to send and receive date.
In an app that recevie data, code is below:
receiver app:
UDPSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
bufferSize= 1024
EnginePort=2000
def ReceiveSocket():
global UDPSocket
global AddressPort
global bufferSize
AddressPort = ("127.0.0.2", EnginePort)
# Bind to address and ip
UDPSocket.bind(AddressPort)
print("UDP server up and listening")
bytesAddressPair = UDPSocket.recvfrom(bufferSize)
message = pickle.loads(bytesAddressPair[0])
address = bytesAddressPair[1]
clientMsg = "Message from Client:{}".format(message)
clientIP = "Client IP Address:{}".format(address)
print(clientMsg)
print(clientIP)
while True:
ReceiveSocket()
sending a simple message:
import socket
import pickle
UDP_IP = "127.0.0.2"
UDP_PORT = 2000
MESSAGE = "Hello, World!"
print ("UDP target IP:", UDP_IP)
print ("UDP target port:", UDP_PORT)
print ("message:", MESSAGE)
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
sock.sendto(pickle.dumps(MESSAGE), (UDP_IP, UDP_PORT))
When receive data ,give me this error:
receiver output:
Message from Client:Hello, World!
Client IP Address:('127.0.0.2', 2003)
Traceback (most recent call last):
File "/home/pi/RoomServerTestApps/Engine.py", line 88, in <module>
ReceiveSocket()
File "/home/pi/RoomServerTestApps/Engine.py", line 29, in ReceiveSocket
UDPSocket.bind(AddressPort)
OSError: [Errno 22] Invalid argument
But when the ReceiveSocket() is outside the while true(), app work well.
Please help me about this.
Thanks.
Get bind() out of the loop. You've already bound to the port at first run, that's why the second+ run fails.
AddressPort = ("127.0.0.2", EnginePort)
UDPSocket.bind(AddressPort)
def ReceiveSocket():
...
Related
I have a simple client server program and the server side works but for some reason I can't get the the client to interact to the server. I am able to launch the server and use nc -6 fe80::cbdd:d3da:5194:99be%eth1 2020 and connect to it.
Server code:
#!/usr/bin/env python3
from socket import *
from time import ctime
HOST='::'
PORT = 2020
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET6, SOCK_STREAM)
##tcpSerSock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
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'%(bytes(ctime(), 'utf-8'), data)).encode('utf-8'))
tcpCliSock.close()
tcpSerSock.close()
client code:
#!/usr/bin/python3
from socket import *
def tcp_ipv6():
HOST = 'fe80::cbdd:d3da:5194:99be%eth1'
PORT = 2020
ADDR = (HOST, PORT)
BUFSIZ = 1024
sock = socket(AF_INET6, SOCK_STREAM)
sock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
sock.send(data)
response = sock.recv(BUFSIZ)
if not response:
break
print(response.decode('utf-8'))
sock.close()
tcp_ipv6()
When I run the client code I get:
Traceback (most recent call last):
File "client.py", line 44, in <module>
tcp_ipv6()
File "client.py", line 31, in tcp_ipv6
sock.connect(ADDR)
OSError: [Errno 22] Invalid argument
Edit1:
Thanks to Establishing an IPv6 connection using sockets in python
4-tuple for AF_INET6
ADDR = (HOST, PORT, 0, 0)
sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0)
sock.connect(ADDR)
Still having the same error
Any idea?
Thanks in advance
Some parts of your question have been asked before.
Establishing an IPv6 connection using sockets in python
However, it is not the entire reason why it is not working correctly. If you look at your IPv6 address. fe80::cbdd:d3da:5194:99be%eth1 You can see the %eth1 at the end. That is not part of the internet address. Change HOST to HOST = 'fe80::cbdd:d3da:5194:99be'. And it should work.
I would also like to point out another error in your code. You are attempting to send a string (received from input) over the socket. However, this method only accepts byte like objects. You can add data = data.encode('utf-8') to fix this.
The higher level function - create_connection , to connect to port works in such case. Sample scriptlet is given as follows. Though why sock.connect fails needs to be identified.
HOST = "xxxx::xxx:xxxx:xxxx:xxxx%en0"
PORT = 2020
ADDR = (HOST, PORT)
BUFSIZ = 1024
sock=create_connection(ADDR)
I have tried to create a simple socket program where I can enable back and forth communication between two server sockets. The first iteration runs successfully and then there is one set of message passing that is possible. When it comes to second round of message passing I get the error.
I feel there is some mistake in the IP Address but I could not resolve it.
I have looked here but could not find a solution
OSError: [Errno 99] Cannot assign requested address - py
Python - socket.error: Cannot assign requested address
Any help is deeply appreciated
This is Server 1:
import socket
import requests
host = "127.0.0.1"
#ip address
port_other_send = 5007
#Other's port while sending
port_own_send = 5006
#Our port for sending
port_other_recieve = 5009
#other port for recieving
port_own_recieve = 5008
#our port for recieving
#s = socket.socket()
#s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#s.bind(("", port_own))
#binds the socket element to the IP address and the Port
def main():
send()
def send():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port_own_send))
s.connect((host,port_other_recieve))
message = input("Type message to be sent ")
while message != "q":
s.send(message.encode('utf-8'))
break
receive()
def receive():
print("This works yo")
socketva = socket.socket()
socketva.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socketva.bind((host, port_own_recieve))
socketva.listen()
c,addr=socketva.accept()
x = True
while x ==True:
print("Connection from",(addr))
data = c.recv(1024)
print ("Data recieved ", str(data))
response= ("Data recieved")
c.send(data)
x = False
c.close
send()
if __name__ == "__main__":
main()
This is server 2:
import socket
import flask
host = "127.0.0.1"
#ip address
port_other_send= 5006
#Other's port while sending
port_own_send= 5007
#Our port for sending
port_other_recieve = 5008
#other port for recieving
port_own_recieve=5009
#our port for recieving
#binds the socket element to the IP address and the Port
def main():
receive()
def receive():
socketva = socket.socket()
socketva.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socketva.bind((host, port_own_recieve))
socketva.listen()
c,addr=socketva.accept()
x = True
while x== True:
print("Connection from",(addr))
data = c.recv(1024)
print ("Data recieved: ",data)
response= ("Data recieved")
c.send(data)
x= False
c.close
send()
def send():
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port_own_send))
s.connect(("",port_other_recieve))
message = input("Enter reply message ")
while message != "q":
s.send(message.encode('utf-8'))
receive()
if __name__ == "__main__":
main()
Server 1 Output:
Type message to be sent hi
This works yo
Connection from ('127.0.0.1', 5007)
Data recieved b'hihihihihihihihihihihihihihihihihi'
Traceback (most recent call last):
File "Server_socket.py", line 100, in <module>
main()
File "Server_socket.py", line 57, in main
send()
File "Server_socket.py", line 68, in send
receive()
File "Server_socket.py", line 87, in receive
send()
File "Server_socket.py", line 63, in send
s.connect((host,port_other_recieve))
OSError: [Errno 99] Cannot assign requested address
Server 2 Output:
Connection from ('127.0.0.1', 5006)
Data recieved: b'hi'
Enter reply message hi
Traceback (most recent call last):
File "Server_socket2.py", line 54, in <module>
main()
File "Server_socket2.py", line 23, in main
receive()
File "Server_socket2.py", line 41, in receive
send()
File "Server_socket2.py", line 50, in send
s.send(message.encode('utf-8'))
ConnectionResetError: [Errno 104] Connection reset by peer
Hello so I am making a python socket server and client and I am trying to figure out how I can make it so when the server sends a message to the client using arguments(I am not good with explaining myself) but basically my issue is this
Server Console:
Command: >senddata 127.0.0.1 32
Clients Response:
Command Accepted!
Traceback (most recent call last):
File "C:\Users\Goten\Desktop\client\client.py", line 18, in <module>
ip = sys.argv[1]
IndexError: list index out of range
I am sending 32 bytes of data(I think) to 127.0.0.1 and it wont work
This is my clients code:
import socket
import sys
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 8888
socket.connect((host, port))
while True:
msg = socket.recv(1024)
if ">senddata".lower() in msg:
print("Command Accepted!")
ip = sys.argv[1]
datasize = sys.argv[2]
data = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = 80
data.sendto(datasize, (ip, port))
print("Sent")
I seriously cannot figure out what I am doing wrong
You are reading from msg, not sys.argv.
if ">senddata".lower() in msg:
print("Command Accepted!")
ip = msg.split(" ")[1]
datasize = msg.split(" ")[2]
I am new in working with python and working on API of XenServer
I am trying to start a script which uses the XenServer API to start a virtual machine upon receiving the data from the client. The code is below
import socket
import json
import startvm
ip = socket.gethostbyname(socket.gethostname())
print("ip of server machiene = " + ip )
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 9999
# bind to the port
serversocket.bind((host, port))
print ("server is waiting for data")
# queue up to 5 requests
serversocket.listen(5)
running = True
while True:
# establish a connection
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
while running:
receivedData = clientsocket.recv(1024)
#json = receivedData
if receivedData:
print (receivedData)
execfile(startvm.py)
else:
print (" -- data end --" )
running = False
serversocket.close()
I am using execute(script name). and it gives me the following error
on the server side script
ip of server machine = 192.168.0.11
server is waiting for data
Traceback (most recent call last):
Got a connection from ('127.0.0.1', 50128)
File "/Users/jasmeet/IdeaProjects/vKey-cloud/server.py", line 45, in
<module>
0
execfile(startvm.py)
AttributeError: 'module' object has no attribute 'py'
and this on client script
connecting to server at 127.0.0.1 on port 9999
Traceback (most recent call last):
File "/Users/jasmeet/IdeaProjects/vKey-cloud/client.py", line 27, in
<module>
clientSocket.send(str(x))
socket.error: [Errno 32] Broken pipe
can anybody explain me how to do it exactly thank you in advance
you could import the file at the beginning like:
from startvm.py import A_FUNCTION_FROM_THAT_FILE
so that it's optimized
and replace
execfile(startvm.py)
with
A_FUNCTION_FROM_THAT_FILE(*args)
ex:
# script A.py
from B.py import customfunc
customfunc(2, 4)
# script B.py
def customfunc(x, y):
return x*y
writing the following code for server.py solved my problem
# server.py
import socket
import json
import startvm
ip = socket.gethostbyname(socket.gethostname())
print("ip of server machiene = " + ip )
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
#host = socket.gethostname()
#port = 9999 # port 80
host = "127.0.0.1"
port = 9999
# bind to the port
serversocket.bind((host, port))
print ("server is waiting for data")
# queue up to 5 requests
serversocket.listen(5)
while True:
running = True
# establish a connection
clientsocket, addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
while running:
receivedData = clientsocket.recv(1024)
#json = receivedData
if receivedData:
print (receivedData)
#execfile('startvm.py')
else:
print (" -- data end --" )
running = False
I have to create a web server in Python. Below is the code I am working on. When i execute it, I initially get no error and it prints "Ready to serve.." , but after opening a browser and running http://10.1.10.187:50997/HelloWorld.html (HelloWorld is an html file in the same folder as my python code, while 10.1.10.187 is my IP address and 50997) is the server port), I get a TypeError saying 'a bytes like object is required and not str". please help me in resolving this and kindly let me know if any other modifications are required.
#Import socket module
from socket import *
#Create a TCP server socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)
# Assign a port number
serverPort = 50997
serverSocket = socket(AF_INET, SOCK_STREAM)
#serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print ("hostname is: "), gethostname()
#print ("hostname is: "), socket.gethostname()
# Bind the socket to server address and server port
serverSocket.bind(("", serverPort))
# Listen to at most 1 connection at a time
serverSocket.listen(1)
# Server should be up and running and listening to the incoming connections
while True:
print ("Ready to serve...")
# Set up a new connection from the client
connectionSocket, addr = serverSocket.accept()
try:
# Receives the request message from the client
message = connectionSocket.recv(1024)
print ("Message is: "), message
filename = message.split()[1]
print ("File name is: "), filename
f = open(filename[1:])
outputdata = f.read()
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.send("\r\n")
# Close the client connection socket
connectionSocket.close()
except IOError:
# Send HTTP response message for file not found
connectionSocket.send("HTTP/1.1 404 Not Found\r\n\r\n")
connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n")
# Close the client connection socket
connectionSocket.close()
serverSocket.close()
The error I am exacly getting-
Ready to serve...
Message is:
File name is:
Traceback (most recent call last):
File "intro.py", line 56, in <module>
connectionSocket.send("HTTP/1.1 200 OK\r\n\r\n")
TypeError: a bytes-like object is required, not 'str'
You need to convert the string you are sending into bytes, using a text format. A good text format to use is UTF-8. You can implement this conversion like so:
bytes(string_to_convert, 'UTF-8')
or, in the context of your code:
connectionSocket.send(bytes("HTTP/1.1 404 Not Found\r\n\r\n","UTF-8"))
connectionSocket.send(bytes("<html><head></head><body><h1>404 Not Found</h1></body></html>\r\n","UTF-8"))`