BluetoothSocket connection 'Invalid Argument' error - python

I am trying to connect and send data from my laptop to my Android phone via Bluetooth. I am using PyBluez library for that. When I am trying to call 'connect' method of BluetoothSocket:
sock=BluetoothSocket( RFCOMM )
sock.connect((host, port))
it always gives me the same error:
Traceback (most recent call last):
File "rfcomm-client.py", line 41, in <module>
sock.connect((host, port))
File "<string>", line 5, in connect
bluetooth.btcommon.BluetoothError: (22, 'Invalid argument')
As I understood from docs and examples, the type of host should be String, and port should be int. That I checked.
I also checked the validity of both port and host, and already paired my devices.
Could anybody help me with this issue?

Related

WinError 10061 and WinError 10022 in socket programming only on Windows

I have a very simple Python code for bind or connect to a port. it works without any error on Ubuntu and CentOs but I have an error on Windows 10. I turned off the firewall and antivirus but it didn't help.
my code:
import socket
port = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
try:
s.connect((host,port))
except:
s.bind((host, port))
s.listen(1)
print("I'm a server")
clientsocket, address = s.accept()
else:
print("I'm a client")
error on windows 10:
Traceback (most recent call last):
File "win.py", line 11, in <module>
s.connect((host,port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
During the handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "win.py", line 13, in <module>
s.bind((host, port))
OSError: [WinError 10022] An invalid argument was supplied
Edit:
I found my problem is in Try... Except part, if I put this code in two files my problem will solve. But Why? try except don't work correctly in Windows?
The connect() fails because there is no server socket listening at (host,port).
The bind() fails because you can't bind to a hostname, only to an IP address. Unless you want to listen on just a specific network interface, you should bind to 0.0.0.0 to listen on all interfaces.

UDP Socket using IPV6

Hello everyone, I am implementing a bittorrent client and i have hit a roadblock.
Here is my code to get the peer list from a particular tracker which only deals in ipv6.
tracker = "udp://tracker.birkenwald.de:6969/announce"
parse = urlparse(tracker)
ip, port = (socket.getaddrinfo(parse.hostname, parse.port, 0, 0, socket.SOL_TCP))[0][4][0], parse.port
#ip, port = 2001:1b10:1000:8101:0:242:ac11:2,6969
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.sendto(tracker_connection.bytestringForConnecting(), (ip, port))
#bytestringForConnecting() is a function for getting the byte version as written in the protocol.
Getting the following error
Traceback (most recent call last):
File "main.py", line 17, in <module>
t.get_peer_list()
File "/home/aditya/Desktop/CN/CN PROJECT/tracker.py", line 21, in get_peer_list
self.udp_request(url)
File "/home/aditya/Desktop/CN/CN PROJECT/tracker.py", line 64, in udp_request
sock.sendto(tracker_connection.bytestringForConnecting(), (ip, port))
socket.gaierror: [Errno -9] Address family for hostname not supported
The python socket documentation says that AF_INET6 addresses must be passed as a tuple of 4 values. If you pass a 2-tuple it'll be interpreted as AF_INET (IPv4) address.

I cant make my python server run with my IPV 4 address

import socket
PORT = 5050
SERVER = "Insert my public IPV4 address here"
ADDR = (SERVER, PORT)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR) #here is the line I get the error for
The error says:
Traceback (most recent call last):
File "The Directory", line 15, in <module>
server.bind(ADDR)
OSError: [WinError 10049] The requested address is not valid in its context
Can I not use my IPV4 to make the server public?
If not then what do I use?

Sending UDP requests through Tor (SOCKS5) with Python

So I have a python script that needs to send a packet to my server 'x.x.x.x'. I've been able to successfully initialise Tor through Python by setting up the SOCKS5 proxy, but upon trying to send a packet to my server I get the error:
Traceback (most recent call last):
File "test.py", line 18, in <module>
sock.sendto(bytes, ("x.x.x.x", 6000))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 338, in sendto
self.bind(("", 0))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 325, in bind
_, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 494, in _SOCKS5_request
raise SOCKS5Error("{0:#04x}: {1}".format(status, error))
socks.SOCKS5Error: 0x07: Command not supported, or protocol error
From what I've seen, socket/SOCKS5 doesn't support connectionless UDP, so I attempted connecting to the port and then sending the packet once connected. I still get the same error as seen above, output can be seen below.
Traceback (most recent call last):
File "test.py", line 18, in <module>
sock.connect(("x.x.x.x", 6000))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 698, in connect
self.bind(("", 0))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 325, in bind
_, relay = self._SOCKS5_request(self._proxyconn, UDP_ASSOCIATE, dst)
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 494, in _SOCKS5_request
raise SOCKS5Error("{0:#04x}: {1}".format(status, error))
socks.SOCKS5Error: 0x07: Command not supported, or protocol error
Seeing as a UDP connection does not work either, I would prefer to stay connectionless as this makes my intended use simpler as the port is not necessarily active/open at any given time. The script I'm using to attempt to send the packet can be seen below. I've added but commented out the connectionless and connection methods I was using. Ignore all the extra imports at the top, these are for use later in the script development.
import socks
import socket
import requests
from TorCtl import TorCtl
import urllib2
import random
import math
import time
socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_SOCKS5, addr="127.0.0.1", port=9050)
socket.socket = socks.socksocket
print requests.get("http://icanhazip.com").text
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
bytes=random._urandom(1024)
# UDP CONNECTION METHOD
#sock.connect(("x.x.x.x", 6000))
#sock.send(bytes)
# UDP CONNECTIONLESS METHOD
#sock.sendto(bytes, ("x.x.x.x", 6000))
Which brings me to my question - is there any way to send UDP packets via a connectionless method through a SOCKS5 proxy in python?
UPDATE
I originally had SocksiPy installed instead of PySocks, so I've replaced the modules and removed the monkeypatch in the original script. But now, I'm instead getting 'Broken Pipe' errors, as seen below.
Traceback (most recent call last):
File "test.py", line 19, in <module>
s.sendto(bytes, ("x.x.x.x", 6000))
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 336, in sendto
return _BaseSocket.sendto(self, bytes, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/socks.py", line 223, in <lambda>
return lambda self, *pos, **kw: self._savedmethods[name](*pos, **kw)
socket.error: [Errno 32] Broken pipe
I've double checked to make sure Tor is actually working and the proxy is up, which it is as I can receive HTTP requests and responses through the Tor proxy - the responses to sites like http://icanhazip.com/ return a different IP that my actual IP, which suggests that Tor is indeed functioning. I also figured that removing the monkeypatch might make it work with better compatibility, seeing as with the new PySocks module on the OLD script it still fails with the original errors seen above.
The new script:
import socks
import socket
import random
import math
s = socks.socksocket()
s.set_proxy(socks.SOCKS5, "localhost", 9050)
bytes=random._urandom(1024)
# UDP CONNECTION METHOD
#sock.connect(("x.x.x.x", 6000))
#sock.send(bytes)
# UDP CONNECTIONLESS METHOD
#s.sendto(bytes, ("x.x.x.x", 6000))
The errors I'm describing above are with the connectionless method - using the connection method seems to possibly work, however it hangs when connecting to the port (which is the be expected, as the port isn't open).
As #gwyn pointed out, Tor only supports TCP streams, as specified on their website. Using UDP over Tor will not work, only TCP connections.

What is the correct way to use source_address

I have come across a corner in socket in Python3.5. When running the code below something is wrong and an error is thrown.
import socket
print(socket.create_connection(('www.baidu.com', 80), source_address=('127.0.0.1', 8998)))
Error:
Traceback (most recent call last):
File "demo.py", line 4, in <module>
print(socket.create_connection(('www.baidu.com', 80), source_address=('127.0.0.1', 8998)))
File "/usr/local/lib/python3.5/socket.py", line 707, in create_connection
raise err
File "/usr/local/lib/python3.5/socket.py", line 698, in create_connection
sock.connect(sa)
OSError: [Errno 22] Invalid argument
Short answer is don't!
You can't play with low level Python sockets not knowing how BSD TCP stack is working and how to use BSD sockets.
The source_address is - as it clearly states - source address and port for you connection. You MUST NOT make connection from loopback interface address to the address in the outside world.
So, the invalid argument error is correct.
Do you really need to set source_address? Why don't let that to the operating system?
You can't use the source address 127.0.0.1. The server can't reach you on this address, its just locally on your computer. This is your local loopback address. You have to use your public IP address.
So best is let the system set the source address like the other answer says.
socket.create_connection(('www.baidu.com', 80))

Categories

Resources