Python socket.error - python

I found this script on aaronbell.com with which I´m trying to use my Dashbutton to connect to IFTTT. My Pi is throwing this error:
Traceback (most recent call last):
File "dash.py", line 30, in <module>
rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
File "/usr/lib/python2.7/socket.py", line 187, in __init__
_sock = _realsocket(family, type, proto)
socket.error: [Errno 1] Operation not permitted
and here is my script:
import socket
import struct
import binascii
import time
import json
import urllib2
ifttt_key = 'loremipsum'
ifttt_url_button = 'https://maker.ifttt.com/trigger/button_was_pressed/with/key/' + ifttt_key
macs = {
'AC63BEBA94E1' : 'MiXT4Pi'
}
def trigger_url(url):
data = '{ "value1" : "' + time.strftime("%Y-%m-%d") + '", "value2" : "' + time.strftime("%H:%M") + '" }'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()
return response
def button_was_pressed():
print 'triggering button event, response: ' + trigger_url(ifttt_url_button)
rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
while True:
packet = rawSocket.recvfrom(2048)
ethernet_header = packet[0][0:14]
ethernet_detailed = struct.unpack("!6s6s2s", ethernet_header)
# skip non-ARP packets
ethertype = ethernet_detailed[2]
if ethertype != '\x08\x06':
continue
# read out data
arp_header = packet[0][14:42]
arp_detailed = struct.unpack("2s2s1s1s2s6s4s6s4s", arp_header)
source_mac = binascii.hexlify(arp_detailed[5])
source_ip = socket.inet_ntoa(arp_detailed[6])
dest_ip = socket.inet_ntoa(arp_detailed[8])
if source_mac in macs:
#print "ARP from " + macs[source_mac] + " with IP " + source_ip
if macs[source_mac] == 'MiXT4Pi':
button_was_pressed()
else:
print "Unknown MAC " + source_mac + " from IP " + source_ip
I tried changing line 30 to:
rawSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.htons(0x0003))
but a similar error occures:
Traceback (most recent call last):
File "dash.py", line 30, in <module>
rawSocket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.htons(0x0003))
File "/usr/lib/python2.7/socket.py", line 187, in __init__
_sock = _realsocket(family, type, proto)
socket.error: [Errno 22] Invalid argument
Thanks in advance for your help!

CHANGE THE LINE
rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(0x0003))
TO THIS
rawSocket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, 0)
This will work.
First, domain should be set to "AF_INET", just like in the struct sockaddr_in (above.) Next, the type argument tells the kernel what kind of socket this is: SOCK_STREAM or SOCK_DGRAM. Finally, just set protocol to "0" to have socket() choose the correct protocol based on the type. (Notes: there are many more domains than I've listed. There are many more types than I've listed. See the socket() man page. Also, there's a "better" way to get the protocol. See the getprotobyname() man page.)

Related

TypeError: descriptor 'bind' requires a '_socket.socket' object but received a 'tuple'

I am trying to make a simple socketing server and client by Python.But when I run the Server code,It shows
Traceback (most recent call last):
File "G:/Python/pyProject/TestOfConnection/socket_sever_pickle.py", line 33, in <module>
Server_PIC(Server_IP, Server_Port)
File "G:/Python/pyProject/TestOfConnection/socket_sever_pickle.py", line 8, in Server_PIC
socket.bind((ip,port))
TypeError: descriptor 'bind' requires a '_socket.socket' object but received a 'tuple'
Here it is:
from socket import *
from io import BytesIO
import pickle
def Server_PIC(ip, port):
socket_obj = socket(AF_INET, SOCK_STREAM)
socket.bind((ip,port))
socket_obj.listen(10)
file_no = 1
while True:
connection, address = socket_obj.accept()
print("server connect by:", address)
recieved_message = b''
recieved_message_fragment = connection.recv(1024)
while recieved_message_fragment:
recieved_message += recieved_message_fragment
recieved_message_fragment = connection.recv(1024)
try:
obj = pickle.loads(recieved_message)
print(obj)
except EOFError:
file_name = 'recv_image_' + str(file_no) + '.bmp'
recv_image = open(file_name, 'wb')
recv_image.write(recieved_message)
recv_image.close()
connection.close()
if __name__ == '__main__':
Server_IP = '0.0.0.0'
Server_Port = 6666
Server_PIC(Server_IP, Server_Port)
I also try to Google this question and modify the code,but it will cause a series of problems.
So could any of you help me figure out what is going on wiht my code. Thanks in advance!
When I modify the code,the error disappeared.
# from socket import *
import socket
from io import BytesIO
import pickle
def Server_PIC(ip, port):
# socket_obj = socket(AF_INET, SOCK_STREAM)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((ip,port))
s.listen(10)
file_no = 1
while True:
connection, address = s.accept()
print("server connect by:", address)
recieved_message = b''
recieved_message_fragment = connection.recv(1024)
while recieved_message_fragment:
recieved_message += recieved_message_fragment
recieved_message_fragment = connection.recv(1024)
try:
obj = pickle.loads(recieved_message)
print(obj)
except EOFError:
file_name = 'recv_image_' + str(file_no) + '.bmp'
recv_image = open(file_name, 'wb')
recv_image.write(recieved_message)
recv_image.close()
connection.close()
if __name__ == '__main__':
Server_IP = '0.0.0.0'
Server_Port = 6666
Server_PIC(Server_IP, Server_Port)

how can i fix addr is not defined in python

I want to make a app like traceroute. I am trying to find routers IP adresses which i passed until i reach the machine and save them in my rota file. But i am taking addr is not defined error. I searched , usually they are giving addr = None but this is causing -'NoneType' object is not subscriptable- error. How can i fix it ?
This is my code:
import sys
import socket
dst = sys.argv[1]
dst_ip = socket.gethostbyname(dst)
f = open("rota.txt","w")
timeout = 0.2
max_hops = 30
ttl=1
port = 11111
while True:
receiver = socket.socket(family=socket.AF_INET,type=socket.SOCK_RAW,proto=socket.IPPROTO_ICMP)
receiver.settimeout(timeout)
receiver.bind(('',port))
sender = socket.socket(family=socket.AF_INET,type=socket.SOCK_DGRAM,proto=socket.IPPROTO_UDP)
sender.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
sender.sendto(b'',(dst_ip,port))
try:
data, addr = receiver.recvfrom(512)
f.write('\n' + str(addr[0]))
except socket.error:
pass
finally:
receiver.close()
sender.close()
ttl += 1
if ttl > max_hops or addr[0] == dst_ip:
break
And my errors:
Traceback (most recent call last):
File "rota.py", line 33, in <module>
if ttl > max_hops or addr[0] == dst_ip:
NameError: name 'addr' is not defined

socket.gaierror: Errno 11004 getaddrinfo failed

i am trying to create a proxy server script with python when i run it i have this arror messages please can i know what are the mistakes i've done and how to avoid them (i sow the script on a site)
how the script looks like !
import socket
from thread import *
import sys
host = ""
port = 91
def start():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)
print "[+] listening ..."
while True:
try:
connection, address = s.accept()
data = connection.recv(1024)
start_new_thread(conn_string, (data, connection))
except KeyboardInterrupt:
print "\n\nclosing !"
def conn_string(data, con):
webserver = ""
portserver = 0
f_li = data.split('\n')[0]
lien = f_li.split(' ')[1]
http_pos = lien.find("://")
if http_pos == -1:
url = lien
else:
url = lien[(http_pos+3):]
port_pos = url.find(':')
if port_pos == -1:
portserver = 80
else:
portserver = url[(port_pos+1):]
s_pos = url.find('/')
if s_pos == -1:
webserver = url
else:
webserver = url[:(s_pos)]
proxy_server(webserver, portserver, data, con)
def proxy_server(webserver, portserver, data, con):
print webserver
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((webserver, int(portserver)))
s.send(data)
while True:
red = s.recv(8192)
if len(red) > 0:
con.send(red)
start()
this is one of the error messages that i have !
Unhandled exception in thread started by <function conn_string at 0x0248CEF0>
Traceback (most recent call last):
File "C:\Users\none2\Desktop\Nouveau dossier\Target.py", line 52, in conn_stri
ng
proxy_server(webserver, portserver, data, con)
File "C:\Users\none2\Desktop\Nouveau dossier\Target.py", line 57, in proxy_ser
ver
s.connect((webserver, int(portserver)))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno 11004] getaddrinfo failed
can you replace
start_new_thread(conn_string, (data, connection))
line with
start_new_thread(conn_string(data, connection))
tried running the same file, it seems above one is the only error

python error: [Errno 32] Broken pipe in Socket.sendall()

I am writing a multi-threaded client/server program. It splits a large file into smaller files in its client side and sends the smaller files to the server concurrently.
The problem is that in every run, the server can only receive two of the smaller files (the first one and another random one). Meanwhile, I encounter the error: "[Errno 32] Broken pipe" in client side of the program in s.sendall(part). The error arises in every thread that starts to send one of the smaller files before reception of the first file (on the server). In other words, every thread that starts to send after the reception the first file (on the server) can complete its task.
I run each of the client and server codes on different computers (both have the following specification: Ubuntu 14.04 desktop, 64 bit, 16GiB ram)
Client side Error:
Traceback (most recent call last):
File "Desktop/File_transmission/Client.py", line 56, in sendSplittedFile
s.sendall(part)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 32] Broken pipe
Client.py:
import random
import socket
import time
import threading
import errno
import select
import File_manipulation
import sys, traceback
class Client:
nodesIpAddr = ["....", "...."] #Server = ....
dataPort = 45678
delay = 2
inputFileAddress = 'tosend.dat'
fileOutputPrefix = 'output'
fileOutputSuffix = ".dat"
bufferSize = 2048
max_size_splitted_file = 10*(2**20) # 10 MiB
def __init__ (self, my_ip):
self.ip = my_ip
def send(self, ip_toSend, dataPort):
print "\tSend function is runing."
totalNumSplittedFile = File_manipulation.split_file(Client.inputFileAddress, Client.fileOutputPrefix, Client.max_size_splitted_file , Client.bufferSize)
for i in range(0, totalNumSplittedFile):
thread_send = threading.Thread(target = self.sendSplittedFile, args = (ip_toSend, dataPort, Client.bufferSize, i, Client.fileOutputPrefix, totalNumSplittedFile))
thread_send.start()
def sendSplittedFile(self, ip_toSend, dataPort, bufferSize, fileNumber, fileNamePrefix, totalNumSplittedFile):
# Create a socket (SOCK_STREAM means a TCP socket)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
BUFFER_SIZE = bufferSize
try:
s.connect((ip_toSend, dataPort))
f = open(fileNamePrefix + '.%s' % fileNumber,'rb')
s.send(str(fileNumber) + " " + str(totalNumSplittedFile))
part = f.read(BUFFER_SIZE)
while (part):
s.sendall(part)
part = f.read(BUFFER_SIZE)
f.close()
s.sendall(part)
time.sleep(Client.delay)
s.sendall('EOF')
print "Done Sending."
print s.recv(BUFFER_SIZE)
s.close()
print "\tData is sent to ", ip_toSend,
except socket.error, v:
traceback.print_exception(*sys.exc_info())
s.close()
nodeIP = [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
n = Client(nodeIP)
n.send(n.nodesIpAddr[0], n.dataPort)
Server Side Error:
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 649, in __init__
self.handle()
File "Desktop/File_transmissionServer.py", line 37, in handle
totalFileNumber = int(details[1])
ValueError: null byte in argument for int()
Server.py
import socket
import time
import threading
import errno
import select
import SocketServer
import File_manipulation
class ServerThreadHandler(SocketServer.BaseRequestHandler):
nodesIpAddr = ["....", "...."] #Server = ....
fileOutputPrefix = 'torec '
fileOutputSuffix = '.dat'
dataPort = 45678
delay = 3
maxNumClientListenedTo = 200
timeout_in_seconds = 5
bufferSize = 2048
totalFileNumber = 0 #Total number of splitted files. It should be set by the incoming packets
def handle(self):
BUFFER_SIZE = ServerThreadHandler.bufferSize # Normally 1024, but we want fast response
# self.request is the TCP socket connected to the client
data = self.request.recv(BUFFER_SIZE)
addr = self.client_address[0]
details = str(data).split()
currentFileNum = int(details[0])
totalFileNumber = int(details[1])
print '\tReceive: Connection address:', addr,'Current File Number: ', currentFileNum, 'Total Number of splitted files: ', totalFileNumber
f = open(ServerThreadHandler.fileOutputPrefix + '_Received.%s' % currentFileNum, 'wb')
data = self.request.recv(BUFFER_SIZE)
while (data and data != 'EOF'):
f.write(data)
data = self.request.recv(BUFFER_SIZE)
f.close()
print "Done Receiving." ," File Number: ", currentFileNum
self.request.sendall('\tThank you for data. File Number: ' + str(currentFileNum))
if __name__ == "__main__":
HOST, PORT = ServerThreadHandler.nodesIpAddr[0], ServerThreadHandler.dataPort # HOST = "localhost"
server = SocketServer.TCPServer((HOST, PORT), ServerThreadHandler)
# Activate the server; this will keep running until you interrupt the program with Ctrl-C
server.serve_forever()

What does this socket.gaierror mean?

I'm new to python and going through a book, Core Python Applications 3rd Edition. This is the the first example and already I'm stumped with it. Here's the code with the error at the end.
#!/usr/bin/env python
from socket import *
from time import ctime
HOST = ' '
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
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" % (ctime(), data))
tcpCliSock.close()
tcpSerSock.close()
Traceback (most recent call last):
File "tsTserv.py", line 12, in <module>
tcpSerSock.bind(ADDR)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
socket.gaierror: [Errno 8] nodename nor servname provided, or not known
What does this mean?
It means that your given host name ' ' is invalid (gai stands for getaddrinfo()).
As NPE already states, maybe an empty string '' would be more appropriate than a space ' '.
The
HOST = ' '
should read
HOST = ''
(i.e. no space between the quotes).
The reason you're getting the error is that ' ' is not a valid hostname. In this context, '' has a special meaning (it basically means "all local addresses").

Categories

Resources