我是python的新手。所以问题似乎很愚蠢。
我想在python中为客户端和服务器实现一个简单的程序。
server.py是
import socket
#s = socket.socket()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, 25, "wlan0"+'\0')
host = socket.gethostname()
port = 12345
s.bind((host,port))
s.listen(5)
while True:
c,addr = s.accept()
print "Got connection from",addr
c.send("Thank you for connecting")
c.close()
client.py是
import socket
#s = socket.socket()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, 25, "wlan0"+'\0')
host = socket.gethostname()
port = 12345
s.connect((host,port))
print s.recv(1024)
s.close
问题是编译器显示错误"不允许操作"。我尝试以root身份执行程序。错误消失了,但没有建立客户端和服务器连接。
在添加此行之前一切正常
s.setsockopt(socket.SOL_SOCKET, 25, "wlan0"+'\0')
希望有人可以解决我的问题。 我想通过wlan0接口连接客户端和服务器。
感谢。
答案 0 :(得分:1)
服务器PY:
import socket
import fcntl
import struct
#s = socket.socket()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
host = get_ip_address("eth0")#replace with "wlan0"
port = 12345
s.bind((host,port))
s.listen(5)
while True:
c,addr = s.accept()
print "Got connection from",addr
c.send("Thank you for connecting")
c.close()
客户PY:
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
#s = socket.socket()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = get_ip_address("eth0")#replace with "wlan0"
port = 12345
s.connect((host,port))
print s.recv(1024)
s.close
check this。 警告:服务器py在shell上运行(" python server.py"),客户端在空闲时运行。