'TypeError when using AF_INET in the sockets library

I am using the socket library for Python. I'm trying to make a local server. The server runs correctly, but the client does not. When I say that I want to connect to AF_INET it gives me a TypeError. It says that the AF_INET address must be a tuple, when it is a string.

Here is my code:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(socket.gethostname())
print("client successfully started")
msg = s.recv(1024)
print(msg.decode("utf-8"))

I am using version 3.10.0 (of python), if that helps.



Solution 1:[1]

From the socket documentation:

  • A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in internet domain notation like 'daring.cwi.nl' or an IPv4 address like
    '100.50.200.5', and port is an integer.

    • For IPv4 addresses, two special forms are accepted instead of a host address: '' represents INADDR_ANY, which is used to bind to all interfaces, and the string '<broadcast>' represents
      INADDR_BROADCAST. This behavior is not compatible with IPv6, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.

For a local server, you can just use 'localhost' for the client.

Example:

from socket import *

PORT = 5000

# for server
s = socket()  # AF_INET and SOCK_STREAM are the default
s.bind(('',PORT))  # must be a 2-tuple (note the parentheses)
s.listen()
c,a = s.accept()

# for client
s = socket()
s.connect(('localhost',PORT))

Solution 2:[2]

The connect function takes in a tuple, so you need an extra set of parentheses. It's not clear what you are trying to do with gethostname. Also, you need to have a port number to connect to. If you are trying to listen to localhost, the code would look like this:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Add socket.gethostbyname and add port number
s.connect((socket.gethostbyname(socket.gethostname()), 8089)) # Add another set of parentheses as you need a tuple
print("client successfully started")
msg = s.recv(1024)
print(msg.decode("utf-8"))

Even this may result in a ConnectionRefusedError: [Errno 61] Connection refused error, because you might have to to use the IP address from the server. Something like: 192.168.0.1. To get your IP address, do ipconfig in your cmd prompt (on Windows).

So the correct code would look like this:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect('192.168.0.1', 8089)) # Your IP instead of 192.168.0.1
print("client successfully started")
msg = s.recv(1024)
print(msg.decode("utf-8"))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark Tolonen
Solution 2 Peter Mortensen