I used python to analyze the online ad system. I try to connect to the server but failed, the template of the code I run in terminal is: python client.py username portnumber,
here is the code on server side:
import sys
import time
import socket
TIMEOUT = 30
class Firefly:
def __init__(self, port):
self._port = port
def _get_the_dataz(self, s):
ret = ""
s.settimeout(TIMEOUT)
while True:
data = s.recv(4096)
if not data:
break
ret = ret + data;
return ret
def _send_command(self, command, retries=3):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.connect(('127.0.0.1', self._port))
s.connect(('localhost', self._port))
s.send(command)
ret = self._get_the_dataz(s)
s.close()
return ret
except socket.error as ex:
print "Firefly timeout, %d retries left" % retries
print str(ex)
if retries == 0:
print "Can't reach firefly on port %d!" % self._port
raise
retries -= 1
time.sleep([30, 10, 2][retries])
return self._send_command(command, retries)
def get_visual_elements(self, url):
return self._send_command('GOTO %s' % url)
It always returns like this:
[errno 111] connection refused
cannot reach server on port 80
traceback(most recent call last):
file "server.py", line 27, in _send_command
s.connect(('localhost', self._port))
file "server.py", line 224, in meth
return getattr(self._sock,name)(*args)
then I try "telnet 127.0.0.1 80",
It returns:
unable to connect to the remote host, connection refused.
What should I do?
Related
I've got an XML file from which I parse a host adress + port. My script is supposed to establish a connection to every host over the given port (only port 22 ATM) to check the availability of the devices. Every host with which a connection is not possible is to be noted in a List.
file = minidom.parse('Sessions.XML')
sessiondata_all = file.getElementsByTagName('SessionData')
failed_ips = []
def check_port(host, port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind(('', 22))
sock.listen(1)
sock.accept()
if not sock.connect_ex((host, int(port))) == 0:
failed_ips.append(host)
sock.close()
def main():
try:
for sessiondata in sessiondata_all:
host = sessiondata.attributes['Host'].value
port = sessiondata.attributes['Port'].value
print(host + ":" + port)
check_port(host, port)
except Exception as e:
logging.error(traceback.format_exc())
print(failed_ips)
if __name__ == '__main__':
main()
This code is successful if I run it as a .py or .exe (pyinstaller --onefile [Filename.py]) locally. It also works on a networkdrive as a .py but as soon as I try it as an executable I get the following Error:
PS [Directory on the Networkdrive] .\FailedIps.exe
1.1.1.1
ERROR:root:Traceback (most recent call last):
File "FailedIps.py", line 101, in main
File "FailedIps.py", line 68, in check_port
File "socket.py", line 232, in __init__
OSError: [WinError 10022] An invalid argument was supplied
[]
Anybody got an idea what's the matter here? I can't figure it out
Python and Pyinstaller are on current versions
You should swap out
socket.bind(('',22))
to
socket.bind((host,22))
I am using mailtrap as the smtp server to send emails. However, when I send an email, I receive an error. The log in credentials are correct and I changed the emails for privacy concerns. Note, I am running this on a pycom device directly connected to my laptop.
def sendEmail():
sender = "Private Person <from#mail.com>"
receiver = "A Test User <to#mail.com>"
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "username" # paste your login generated by Mailtrap
password = "password" # paste your password generated by Mailtrap
message = """
Subject: Hi Mailtrap
To: {receiver}
From: {sender}
This is a test e-mail message."""
try:
with smtplib.SMTP(smtp_server, port) as server:
server.login(login, password)
server.sendmail(sender, receiver, message)
print('Sent')
except smtplib.SMTPServerDisconnected:
print('Failed to connect to the server. Wrong user/password?')
except smtplib.SMTPException as e:
print('SMTP error occurred: ' + str(e))
Error Message:
Traceback (most recent call last):
File "<stdin>", line 147, in <module>
File "<stdin>", line 114, in sendEmail
File "<stdin>", line 106, in sendEmail
File "/flash/lib/smtplib.py", line 84, in __init__
File "/flash/lib/smtplib.py", line 110, in connect
AttributeError: 'module' object has no attribute 'IPPROTO_SEC'
>
Line 106 refers to server.login(login, password) and line 114 is the line right after print('SMTP error occurred: ' + str(e))
I have taken the snippet from the smptlib which is causing problems
def connect(self, host, port=0, source_address=None):
if source_address:
self.source_address = source_address
if not port and (host.find(':') == host.rfind(':')):
i = host.rfind(':')
if i >= 0:
host, port = host[:i], host[i + 1:]
try:
port = int(port)
except ValueError:
raise OSError("non numeric port")
if not port:
port = self.default_port
if self.debuglevel > 0:
print('connect:', (host, port), file=stderr)
if self.tls:
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC)
self.sock = ssl.wrap_socket(ss)
else:
self.sock = socket.socket()
self.sock.settimeout(self.timeout)
try:
self.sock.connect(socket.getaddrinfo(host, port)[0][4])
except:
self.close()
(code, msg) = self.getreply()
if self.debuglevel > 0:
print("connect:", msg, file=stderr)
return (code, msg)
Specifically ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_SEC)
Any help would be greatly appreciated, thanks :)
Hello I'm trying to create a P2P program to distribute messages throgh the clients.
My server.py:
import requests
from flask import Flask, jsonify, request
import logging
from daemon import Daemon
import time
import argparse
import sys
from transaction import Transaction
import settings
import socket
import threading
bind_ip = '139.59.26.12'
bind_port = 9998
my_node_addr = str(bind_ip) + ":" + str(bind_port)
clients = [("0.0.0.0", 9999), ("0.0.0.0", 9998)]
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5) # max backlog of connections
print('Listening on {}:{}'.format(bind_ip, bind_port))
numbers = []
def broadcast_info(info):
for n in clients:
node_str_addr = str(n[0]) + ":" + str(n[1])
print("Selected: " + node_str_addr)
if node_str_addr != my_node_addr:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((n[0], n[1]))
client.send(info)
response = client.recv(4096)
def handle_client_connection(client_socket):
request = client_socket.recv(1024)
request_str = request.decode()
if request_str == 'print':
client_socket.send(str(numbers).encode('utf-8'))
print(numbers)
else:
client_socket.send('Added!'.encode('utf-8'))
client_socket.close()
num_rec = int(request.decode())
if num_rec not in numbers:
numbers.append(num_rec)
#broadcast_info(request)
while True:
client_sock, address = server.accept()
print('Accepted connection from {}:{}'.format(address[0], address[1]))
client_handler = threading.Thread(
target=handle_client_connection,
args=(client_sock,)
# without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject
)
client_handler.start()
And my client:
import socket
hostname, sld, tld, port = 'www', 'integralist', 'co.uk', 80
target = '{}.{}.{}'.format(hostname, sld, tld)
# create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect the client
# client.connect((target, port))
client.connect(('139.59.76.32', 9998))
# send some data (in this case a HTTP GET request)
client.send("2".encode('utf-8')) # Number or "print"
# receive the response data (4096 is recommended buffer size)
response = client.recv(4096)
print (response)
client.close()
Sometimes it works well. But then after a few tries this error appears:
Exception in thread Thread-11:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "server.py", line 43, in handle_client_connection
request = client_socket.recv(1024)
File "/usr/local/lib/python3.5/dist-packages/gevent/_socket3.py", line 336, in recv
self._wait(self._read_event)
File "/usr/local/lib/python3.5/dist-packages/gevent/_socket3.py", line 156, in _wait
self.hub.wait(watcher)
File "/usr/local/lib/python3.5/dist-packages/gevent/hub.py", line 651, in wait
result = waiter.get()
File "/usr/local/lib/python3.5/dist-packages/gevent/hub.py", line 898, in get
return self.hub.switch()
File "/usr/local/lib/python3.5/dist-packages/gevent/hub.py", line 630, in switch
return RawGreenlet.switch(self)
gevent.hub.LoopExit: ('This operation would block forever', <Hub at 0x7fdf21aa2af8 epoll pending=0 ref=0 fileno=9>)
I tried everything. In my local machine works fine. But when I try to do it on my Digitalocean VPS, then this happens. I've search about this error over the Internet but I can't find anything that helps me.
Do you know what can be the cause of this error?
Thanks
I'm writing a program that needs communication between two pc's. I know how to connect and send messages to each other. When the user opens the program, it should listen to connections. But if the user clicks 'connect', the program should stop listening for connections and connect to a user instead. How should I achieve that?
I've got this right now:
MAIN
#threaded
def getOnline(self):
# fires when the user opens the program
client.connect(PORT)
#threaded
def connect(self):
# when the user clicks connect
global IS_MASTER
IS_MASTER = True
print('Master:', IS_MASTER)
if IS_MASTER:
client.closeConnection()
server.connect(CLIENT_IP, PORT)
CLIENT
class Client():
def __init__(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self, port):
print('Listening to connections')
self.s.bind(('', port))
self.s.listen(1)
conn, addr = self.s.accept()
print('Connected by:', addr)
def closeConnection(self):
print('Not listening any longer')
self.s.close()
sys.exit()
SERVER
class Server():
def __init__(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def connect(self, host, port):
self.s.connect((host, port))
print('Connected to:', host)
Now when I click 'connect' I get: 'ConnectionAbortedError: [Errno 53] Software caused connection abort'.
Any help would be greatly appreciated!
EDIT
Full Traceback
Exception in thread Thread-1:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 639, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/threading.py", line 596, in run
self._target(*self._args, **self._kwargs)
File "/Users/cedricgeerinckx/Dropbox/Redux/OSX/Redux.py", line 28, in wrapped_f
ret = f(*args, **kwargs)
File "/Users/cedricgeerinckx/Dropbox/Redux/OSX/Redux.py", line 204, in getOnline
client.connect(PORT)
File "/Users/cedricgeerinckx/Dropbox/Redux/OSX/Client.py", line 14, in connect
conn, addr = self.s.accept()
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/socket.py", line 135, in accept
fd, addr = self._accept()
That exception is being thrown inside your getOnline method, which is run on startup. That means the exception is occurring when the connection made in that method is shut down by the connect method. You should just handle the exception inside getOnline:
#threaded
def getOnline(self):
# fires when the user opens the program
try:
client.connect(PORT)
except ConnectionAbortedError as e:
print("Connection shut down!")
I've been programming my chat but then I get an error which crashes the server and so then the next time I won't be able to use the same port and so I get socket.bind error when I run it again. How to fix?
Source code:
import socket
from threading import Thread
def clientHandler():
conn, addr = sock.accept()
print addr, "is Connected"
while 1:
data = conn.recv(1024)
if not data:
break
print "Received Message", repr(data)
HOST = ''
PORT = raw_input('PORT: ')
PORT = int(PORT)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(5)
print "Server is running......"
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
for i in range(5):
Thread(target=clientHandler).start()
sock.close()
This is what happens:
Server is running......
Exception in thread Thread-5:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:/Users/Judicaƫl/Desktop/server_test.py", line 5, in clientHandler
conn, addr = sock.accept()
File "C:\Python27\lib\socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "C:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
>>> ==================================================== RESTART ====================================================
>>>
Traceback (most recent call last):
File "C:/Users/Judicaƫl/Desktop/server_test.py", line 15, in <module>
sock.bind((HOST, PORT))
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
I am using Win7 64bit python 2.7.6 64bit version
and is there also a way to restore the ports which had been blocked or does it auto restore when restart comp?
*******FIXED by Daniel************
Fixed Code:
import socket, sys
from threading import Thread
def clientHandler(conn, addr):
print addr, "is Connected"
while 1:
data = conn.recv(1024)
if data == 'Admin: /server shutdown':
sock.close()
print 'quitting...'
quit()
if not data:
break
conn.sendall(data) # only sends to original sender
print "Received Message", repr(data)
HOST = ''
PORT = int(raw_input('PORT: '))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(999999)
print "Server is running......"
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
for i in range(999999):
conn, addr = sock.accept()
Thread(target=clientHandler, args=(conn, addr)).start()
sock.close()
How do I now send the messages received to all clients?
The functions you have to call at server side is the following:
- create a socket
- bind it to a port
- listen
- accept
- handle the client communication
You have multiple threads for accept. Then you close the socket, so all accepts fail.
The correct way is
while True:
client, addr = sock.accept()
Thread(target=clientHandler, args=(client, addr)).start()