python socket error: AF_INET address must be tuple, not str - python

I have this short program:
import sys
import socket
target = "google.co.uk"
port = 443
print(target)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(target)
print("successfull connection to: " + target)
When I run the code, I get:
s.connect(target)
TypeError: getsockaddrarg: AF_INET address must be tuple, not str
When I tried to change the line to: s.connect(target,443)
I also got an error:
s.connect(target,443)
TypeError: connect() takes exactly one argument (2 given)
What is the problem?

What the function receives as a parameter is a tuple and thus a tuple should be given as a parameter. Meaning instead f(a,b) call the function with f((a,b))
And so, we fix your code like this:
import sys
import socket
target = "google.co.uk"
port = 443
print(target)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((target, port))
print("successfull connection to: " + target)

I was getting the same error. From the connections.py file from PyMySQL there's a function named connect() line with
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(self.connect_timeout)
sock.connect(self.unix_socket)
A Windows user will get
AttributeError: module 'socket' has no attribute 'AF_UNIX'
To fix it one should change the first line to
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
This will then get
File "C:\Users\tiago\Desktop\dev\venv\lib\site-packages\pymysql\connections.py", line 609, in connect
sock.connect(self.windows_socket)
TypeError: connect(): AF_INET address must be tuple, not str
Based on this answer, one just need to have the third line changed to
sock.connect((self.unix_socket))
so you should have
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(self.connect_timeout)
sock.connect((self.unix_socket))

Related

Call variable from other function - sockets

I am new to Python and having issues calling a variable from one func to use in another.
First function gets localhost IP, second function I would like to grab that IP and use it to port scan itself.
My open port function comes up with error 'AttributeError: 'function' object has no attribute 'ipv4''
Any help is greatly appreciated.
def get_IP():
ip = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
ip.connect(("8.8.8.8", 80))
print(ip.getsockname()[0])
ipv4 = ip.getsockname()[0]
ip.close()
return ipv4
def get_open_ports():
for port in range(1,65535):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = s.connect_ex((get_IP.ipv4, port))
if result ==0:
print(f"Port {port} is open")
s.close()
You can pass it as an argument to the second function using the syntax:
def get_open_ports(my_ip):
But you need to call the functions:
ip = get_IP()
open_ports = get_open_ports(ip)
Or even
open_ports = get_open_ports(get_IP())

It seems like socket.bind isn't in the socket module

Here is the error that it is showing
I use windows 7 running python 3.8.6. But it is showing that socket module does not have socket.bind.
you must create socket object first. then you can call socket.bind which state the 'socket' or 's' here as an object, as this example
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
Try socket.socket.bind instead.
Or change import to from socket import socket

Python - show path, simple socket problem

I recently ventured into python in 3.7
I want to make a server / client whose client will show the path I put in input (macOS):
Server
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 1337 # Arbitrary non-privileged port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
info = conn.recv(1024)
print(info)
raw_input("Push to exit")
s.close()
Client :
import socket
import os
HOST = '' # The remote host
PORT = 1337 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print('Connected')
info = os.listdir("/Users/jhon")
s.send(str(info))
s.close()
Server start and it's listening...
python client.py Connected Traceback (most recent call last): File
"client.py", line 10, in
s.send(str(info)) TypeError: a bytes-like object is required, not 'str' (not understand this), and after client start, in server show:
Connected by ('127.0.0.1', 52155) b'' Traceback (most recent call
last): File "server.py", line 13, in
raw_input("press for exit") NameError: name 'raw_input' is not defined (venv) MBP-di-Jhon:untitled1 jhon$
You may want to change the client code to:
HOST = '' # The remote host
PORT = 1337 # The same port as used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
print('Connected')
info = "\n".join(os.listdir("/Users/jhon"))
s.send(info.encode())
s.send(info)
s.close()
os.listdir("/Users/jhon") returns a list, we use join and encode to make it byte object, which is needed for s.send()
You ventured into 3.7 from some 2.x version without modifying the 2.x code. Read something about the differences before continuing. To help you get started:
Replace raw_input with input. (One could replace 2.x input() with eval(input()), but one should nearly always use a more specific evaluator, such as int(input()).)
In 3.x, strings are unicode, whereas sockets still require bytes. Change send and recv to
s.send(str(info).encode())
info = conn.recv(1024).decode()

Python s.recv() returns empty string

I've got a simple client and server I found on an online tutorial
#server.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost' # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
#client # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = 'localhost'
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
When I run my client.py all it does is print an empty string when it should print ('Thank you for connecting'). When I connect localhost 12345 from telnet it sends the message fine so I don't know why my client isn't receiving the message
Any thoughts. I'm very new to socket programming and would love to find a solution so I can move on.
While running your script as is, I got this error:
Waiting connections ...
Got connection from ('127.0.0.1', 63875)
Traceback (most recent call last):
File "serv.py", line 14, in <module>
c.send('Thank you for connecting')
TypeError: a bytes-like object is required, not 'str'
Few things here:
Ensure you're sending bytes instead of str. you could do this by replacing line 14 with:
c.send(b'Thank you for connecting')
Also, it's always useful to declare your sockets s like this:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Further read:
Py2: https://docs.python.org/2/library/socket.html
Py3: https://docs.python.org/3/library/socket.html
Hope it works! :)

python 'TypeError: argument must be string or read-only character buffer, not tuple'

I wrote this code using python 2.7:
class LoadBalancerHandler:
def __init__(self, file_name):
self.server_socket = socket.socket(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
file = open(file_name)
setup_apps(file.read())
def listen(self, host='localhost', port=80):
self.server_socket.bind((host,port))
self.server_socket.listen(5)
while True:
(client_socket, address) = self.server_socket.accept()
threadHandling = ThreadHandling(client_socket, self)
threadHandling.start()
but I get this error:
TypeError: argument must be string or read-only character buffer, not tuple
This error is raised by the line:self.server_socket.bind((host,port))
Again, i think your options to socket.socket(...) are incorrect. If you're trying to create a TCP listener, this works
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('localhost',5555))
s.listen(5)

Categories

Resources