4

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 ...

asked Nov 16, 2012 at 18:31
2
  • Yes .. But it wont work as sock.py either. Commented Nov 16, 2012 at 18:37
  • 1
    Make sure you delete socket.py. If that continues to fail, please update the stacktrace to the one you get with sock.py. Commented Nov 16, 2012 at 18:40

1 Answer 1

13
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.

answered Nov 16, 2012 at 18:36
Sign up to request clarification or add additional context in comments.

1 Comment

haha thanks. now I feel stupid. I'm a python newbie though so lesson learned :) +1

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.