以前也学过套接字编程,这次想系统全面的学习下python网络编程的使用。做这个,为检测进度,也为后续留下笔记和足迹。
socket 常用函数
socket.gethostname()
socket.gethostbyname()
import socket
host = socket.gethostname()
ip = socket.gethostbyname(host)
# 还能够解析出外部服务的ip
ip = socket.gethostbyname('www.baidu.com')
socket.inet_aton()
socket.inet_ntoa()
import socket
socket.inet_aton('127.0.0.1')
socket.inet_ntoa('\x7f\x00\x00\x01')
socket.getservbyport()
import socket
# 找一下http和https的服务,如没有回返回notfound错误
socket.getservbyport(80, 'tcp')
socket.getservbyport(443, 'tcp')
socket.ntohl()/socket.ntohs()
socket.htonl()/socket.htons()
socket.gettimeout()
socket.settimeout()
import socket
# 设置一个套接字对象
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 超时时间默认为空
sock.settimeout(100)
sock.gettimeout()
socket.error() 一般异常
socket.gaierror() 地址异常
socket.timeout() 超时异常
socket.getsockopt()
socket.setsockopt()
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 查询缓冲大小
sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
# 设置大小
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
# 设置重用套接字
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
非阻塞:套接字遇到异常就抛错误socket.setblocking(0)
阻塞:遇到错误不会阻止操作socket.setblocking(1)
import ntplib
import time
ntp = ntplib.NTPClient()
res = ntp.request('pool.ntp.org')
print time.ctime(res.tx_time)
练习套接字 客户端/服务端 简单通信
服务端
import socket
# 初始化一个套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置套接字可重用
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定套接字
sock.bind(('localhost', 8888))
# 监听客户端链接,最大数目为5
sock.listen(5)
while True:
# 阻塞,接收
client, add = sock.accept()
data = client.recv(2048)
print "data:", data, '\n', 'host:', add, '\n'
# 关闭
client.close
客户端
import socket
# 初始化一个套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 链接服务端
sock.connect(('localhost', 8888))
try:
# 发送数据
sock.sendall("From client socket!")
except socket.error, e:
print "error!"
finally:
# 关闭
sock.close()
两个终端通信
服务端
duck@duck:~/sockdir/chapter_1$ python sersock.py
data: From client socket!
host: ('127.0.0.1', 53910)
客户端
duck@duck:~/sockdir/chapter_1$ python clisock.py