2017-08-18 70 views
0

我想學習如何使用本教程中使用套接字:
https://www.tutorialspoint.com/python/python_networking.htm
我已經複製從網站的代碼到我的目錄,並運行它究竟正如在教程中所做的那樣,但卻遇到了錯誤。以下是教程中的代碼。錯誤:節點名稱也不servname提供,或者不知道(蟒蛇插座)

#!/usr/bin/python   # This is server.py file 

import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
host = 'localhost' # Get local machine name 
port = 12345    # Reserve a port for your service. 
s.bind((host, port))  # Bind to the port 

s.listen(5)     # Now wait for client connection. 
while True: 
    c, addr = s.accept()  # Establish connection with client. 
    print("asdf") 
    c.send('Thank you for connecting') 
    c.close()    # Close the connection 

和client.py

#!/usr/bin/python   # This is client.py file 

import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
host = socket.gethostname() # Get local machine name 
port = 12345    # Reserve a port for your service. 

s.connect((host, port)) 
print s.recv(1024) 
s.close      # Close the socket when done 

這是我跑的控制檯命令:

python server.py & 
python client.py 

我運行命令後得到了這個錯誤:

Traceback (most recent call last): 
    File "client.py", line 9, in <module> 
    s.connect((host, port)) 
    File  "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/soc ket.py", line 228, in meth 
return getattr(self._sock,name)(*args) 
socket.gaierror: [Errno 8] nodename nor servname provided, or not known 

在這種情況很有幫助,v我使用的python版爲是Python的2.7.10,我使用的是Mac是10.12.6

感謝版本提前

+0

這看起來像什麼'socket.gethostname的問題()'回報。嘗試使用'host ='localhost''來代替。 –

+0

似乎工作,我現在把其餘的代碼,看看它是否仍然有效 – fred

+0

所以你的修復讓我過去的服務器文件的問題,但客戶端文件仍然無法工作 – fred

回答

1

socket.gethostname文檔:

Return a string containing the hostname of the machine where the Python interpreter is currently executing.

Note: gethostname() doesn’t always return the fully qualified domain name; use getfqdn() for that.

該主機的IP與主機名不一樣。你有兩個選擇:

  1. 您可以手動分配host0.0.0.0localhost

  2. 您還可以查詢socket.gethostbyname

    host = socket.gethostbyname(socket.gethostname()) # or socket.getfqdn() if the former doesn't work 
    
0

我做了一些變化,你的代碼。這裏的server.py

#!/usr/bin/python   # This is server.py file 
import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
host = socket.gethostname() # Get local machine name 
port = 12345    # Reserve a port for your service. 
s.bind((host, port))  # Bind to the port 

s.listen(5) 
c,addr= s.accept() 


print "Got connection from the ", addr 
c.send('Thank you for connecting') 

c.close()    # Close the connection 

這裏的client.py

#!/usr/bin/python   # This is client.py file 

import socket    # Import socket module 

s = socket.socket()   # Create a socket object 
host = socket.gethostname() # Get local machine name 
port = 12345    # Reserve a port for your service. 

s.connect((host, port)) 

msg = (s.recv(1024)) 
print msg 
s.close      # Close the socket when done 

我希望這將有助於

相關問題