AttributeError: type object 'socket' has no attribute 'socket'

im python to make a simple script to connect to another socket server but im having an issue in getting my servers ip using socket before i used socket.getbyhostname(socket.gethostname()) but im getting the error `AttributeError: ‘socket’ object has no attribute ‘gethostname’

ive tried importing everything from socket by using from socket import * but now im getting the error type object 'socket' has no attribute 'socket'

can someone explain whats going on and why this is a problem for me in the firstplace as ive used the same line before with no issues

Full code:

import socket
  
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  
HOSTNAME = socket.getbyhostname(socket.gethostname())
  
print(HOSTNAME)
  
#constantly wait for a connection
print("Waiting for a connection...")
while True:
      #listen for a connection
      socket.bind(("", 9998))
      socket.listen(1)
  
      conn, addr = socket.accept()
      print("Connected to: ", addr[0])

On this line you’ve imported the module and assigned it to the variable socket.

On this line you’ve reassigned a socket object to the variable socket. Now you have no more access to the module. Use a different name for these two things.

2 Likes

Another problem is here:

HOSTNAME = socket.getbyhostname(socket.gethostname())

The method is gethostbyname, rather than getbyhostname.

See socket.gethostbyname(hostname).

Ohhhh okay ive got it now thanks for your help :slight_smile:


Hello Goose and everybody else reading this! Thank you for your attention in advance. I am a Python beginner and I am stuck trying to execute the code shown in the picture attached. I installed Python 3.11.5 in my laptop, I activated the Telnet Client, and then prompted the code as shown in the picture but I always get the same atttribute error. Hey, let me also add that I´ve already corrected the Syntax Errors shown on the parenthesis left to close. I am trying to figure out what I am missing if the code is correct (or not??). Is there any other alternative or shortcut I may use to get my code run with Python? By the way, I am using Bracket as text editor. I´d appreciate so much if you could help me get this error figured out. Any suggestion? I am open to your insights.