Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket isn't working in Python

Tags:

python

I've been trying out the 'socket' module in Python but whenever I attempt to run this code :

import socket
import sys

host = '192.168.1.1'
port = 23

try:
      s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except:
      print "socket() failed"
      sys.exit(1)

Then it dies. Here is the error without the except and try :

Traceback (most recent call last):
  File "C:\Documents and Settings\a\Desktop\socket.py", line 1, in <module>
    import socket
  File "C:\Documents and Settings\a\Desktop\socket.py", line 6, in <module>
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
AttributeError: 'module' object has no attribute 'AF_INET'

I've just started Python(Today) and am in need of help.

I saved it as socket.py but also sock.py ...

like image 207
Red_Hat Avatar asked Dec 12 '22 20:12

Red_Hat


1 Answers

import socket

looks into the current directory before Python's standard library. And since your file is called socket.py, it is itself imported instead of the socket standard library module. Rename (don't copy, since that would leave the original file) the file to something else, such as my_socket.py.

like image 173
phihag Avatar answered Dec 28 '22 02:12

phihag