简体   繁体   中英

Socket isn't working in 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 ...

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM