python odd multicast socket exception - python

I have some example python code that I got from another stack overflow answer (can't remember where), that implements multicasting. The following code should set up a socket object for receiving multicast packets.
I encapsulated it in a class like so:
class Multisock:
def __init__(self, MCAST_GRP, MCAST_PORT, packsize):
import socket
import struct
self.MCAST_GRP = MCAST_GRP
self.MCAST_PORT = MCAST_PORT
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind(('', MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
However, this gives me this error:
Traceback (most recent call last):
File "./Audiorecv.py", line 41, in <module>
sock = MulticastNetworking.Multisock('244.1.1.1', 5007, chunk)
File "/home/wheybags/Multicast-Voice-Chat/MulticastNetworking.py", line 30, in __init__
self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument
Which is really confusing because if I just set MCAST_GRP statically to a string representing an ip, it works, but it gives the error above if I try to use a constructor argument.

The multicast address you're using, 244.1.1.1, is invalid. Multicast addresses range from 224.0.0.0 to 239.255.255.255. I ran your code with 224.1.1.1, a valid address, and it worked just fine.

Related

Python Socket SSL OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (wh

Full error code:
Traceback (most recent call last):
File "C:\path\to\my\python\code\server_ssl_testing.py", line 15, in <module>
response = ssock.recv(1024).decode("utf-8")
File "C:\Program Files\Python39\lib\ssl.py", line 1228, in recv
return super().recv(buflen, flags)
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
I created SSL Socket server and client, but then server try to receive info from client it falied and print error that is above this text.
Server:
import socket
import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_cert_chain('certs/server-cert.pem', 'certs/server.key')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock:
sock.bind(('localhost', 2642))
sock.listen(5)
with context.wrap_socket(sock, server_side=True) as ssock:
conn, addr = ssock.accept()
response = ssock.recv(1024).decode("utf-8")
print(response)
Client:
import socket
import ssl
hostname = 'localhost'
context = ssl.create_default_context()
sock = socket.create_connection((hostname, 2642))
ssock = context.wrap_socket(sock, server_hostname=hostname)
msg = "Hello World!"
ssock.send(msg.encode("utf-8"))
In server.py I should write conn.recv instead of ssock.recv.
Should help if anyone will want do it in future =)

Python Socket getattr requires integer

I'm trying to use the socket object in one of my python codes and it fails at this line:
#!/usr/bin/python
import subprocess,socket
HOST = '127.0.0.1'
PORT = '443'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Yo')
while 1:
data = s.recv(1024)
if data == "quit": break
proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdoutput1 = proc.stdout.read() + proc.stderr.read()
s.send(stdoutput)
s.send('Bye')
s.close()
It fails at: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
TypeError: an integer is required
It's telling me an integer is required in the parameters when I can't see why it would be. It calls this method from socket.py:
def meth(name,self,*args):
return getattr(self._sock,name)(*args)
You have misunderstood the error message, and are looking at the wrong line. It is the s.connect() call that fails:
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('127.0.0.1', '443'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
TypeError: an integer is required
Note that it is not the socket.socket() call that failed here, it is the s.connect() call instead, because '443' is not a valid port number.
Port numbers must be integers, not strings; correct your PORT variable:
PORT = 443 # make this an integer
With that change connecting works (provided the port is connectable):
>>> s.connect(('127.0.0.1', 443))

server.bind(), only local ip address

I can't define a server with the real IP address of my computer, it gives me an error.When I do this with my local IP address it works but I want to run the client in other computer
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('my_ip',9876))
server_socket.listen(1)
(client_socket,client_address)=server_socket.accept()
recived_data=client_socket.recv(999999999)
password=open(r'D:\passwords','wb')
password.write(recived_data)
client_socket.close()
server_socket.close()
the client:
import socket
my_socket = socket.socket()
my_socket.connect(('the_real_ip', 9876))
the error I get is:
Traceback (most recent call last):
File "D:/Heights/Documents/Projects/Cyber/Password_Server.py", line 4, in <module>
server_socket.bind(('my_ip',9876))
File "D:\Heights\PortableApps\PortablePython2.7.6.1\App\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context
You can use server_socket.bind(('0.0.0.0',9876)) and server_socket.bind(('',9876))
Check this link: https://serverfault.com/questions/78048/whats-the-difference-between-ip-address-0-0-0-0-and-127-0-0-1
To connect from outside your LAN, you have to connect to the router of that LAN using the 'outside IP' and make let the router formward the connection to the 'local IP'.

Python client server to send a file Beginner Error

I am trying to do simple code to send file from the client to the server after saving in t some data.
I am a beginner so I can't figure where the problem is or what is the missing function or line in my code
The Server :
import socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8000))
server_socket.listen(0)
BUFFER_SIZE = 1024
conn, addr = server_socket.accept()
print ('Got connection from', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data:
break
fileREC=open (data , 'rb')
The Client
import socket
client_socket = socket.socket()
client_socket.connect(("192.168.1.4", 8000))
BUFFER_SIZE = 1024
TextFile= open ("TextFile","w")
TextFile.write("Here is the file")
TextFile.write("Writing data")
TextFile.close()
f=open (TextFile , 'wb')
print ("Writing the file to binart ")
client_socket .send(f)
print ("Data Sent")
The Error
ERROR:Traceback (most recent call last):
File "tenmay.py", line 5, in <module>
client_socket.connect(("192.168.1.4", 8000))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
Send the contents of the file not the filehandle:
f=open ("TextFile", 'rb')
client_socket.send(f.read())
The second time the client runs the server is waiting to recv data because the accept() command is outside of the loop.
The client could repeatedly send data from a loop, but not if the program ends and has to be restarted.

Why Python does not recognize format function on type string?

I am getting error when trying to run Python socket http server.
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.send(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Error:
C:\Python25>python index.py
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 2506)
Traceback (most recent call last):
File "C:\Python25\lib\SocketServer.py", line 222, in handle_request
self.process_request(request, client_address)
File "C:\Python25\lib\SocketServer.py", line 241, in process_request
self.finish_request(request, client_address)
File "C:\Python25\lib\SocketServer.py", line 254, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "C:\Python25\lib\SocketServer.py", line 521, in __init__
self.handle()
File "index.py", line 15, in handle
print "{} wrote:".format(self.client_address[0])
AttributeError: 'str' object has no attribute 'format'
----------------------------------------
And my client:
import socket
import sys
HOST, PORT = "localhost", 9999
data = " ".join(sys.argv[1:])
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.send(data + "\n")
# Receive data from the server and shut down
received = sock.recv(1024)
finally:
sock.close()
print "Sent: {}".format(data)
print "Received: {}".format(received)
This is example given on Python official website
What is wrong here?
From the Python website:
format(value[, format_spec]) Convert a value to a “formatted”
representation, as controlled by format_spec. The interpretation of
format_spec will depend on the type of the value argument, however
there is a standard formatting syntax that is used by most built-in
types: Format Specification Mini-Language.
New in version 2.6.
So I guess you should upgrade your Python version.
Or use another syntax:
print "%s wrote:" % self.client_address[0]
If self.client_address[0] can be converted to a string.

Categories