------------------------------------------------------------------------------
#1.2打印设备名和IPv4地址
import socket
host_name=socket.gethostname()
print "Host name:%s"%host_name
print "IP address:%s"%socket.gethostbyname(host_name)
------------------------------start
#1_1_local_machine_info.py
import socket
def print_machine_info():
host_name=socket.gethostname()
ip_address=socket.gethostbyname(host_name)
print "Host name:%s"%host_name
print "IP address:%s"%ip_address
if __name__=='__main__':
print_machine_info()
------------------------------end
------------------------------------------------------------------------------
#1.3获取远程设备的IP地址
------------------------------start
#1_2_remote_machine_info.py
import socket
def get_remote_machine_info():
remote_host='www.baidu.com'
try:
print "IP address:%s"%socket.gethostbyname(remote_host)
except socket.error,err_msg:
print "%s:%s"%(remote_host,err_msg)
if __name__=='__main__':
get_remote_machine_info()
------------------------------end
------------------------------------------------------------------------------
#1.4将IPv4地址转换成不同的格式
#1_3_ip4_address_conversion.py
import socket
from binascii import hexlify
def convert_ip4_address():
for ip_addr in['127.0.0.1','192.168.0.1']:
packed_ip_addr=socket.inet_aton(ip_addr)
unpacked_ip_addr=socket.inet_ntoa(packed_ip_addr)
print "IP Address:%s=> Packed:%s,Unpacked:%s"\
%(ip_addr,hexlify(packed_ip_addr),unpacked_ip_addr)
if __name__=='__main__':
convert_ip4_address()
------------------------------------------------------------------------------
#1.5通过指定的端口和协议找到服务名
#1_4_finding_service_name.py
import socket
def find_service_name():
protocolname='tcp'
for port in[80,25]:
print "Port:%s => service name:%s"%(port,socket.getservbyport(port,protocolname())
print "Port:%s => service name:%s"%(53,socket.getservbyport(53,'udp'))
if __name__=='__main__'
find_service_name
------------------------------------------------------------------------------
#1.6主机字节序和网络字节序之间相互转换
#socket库中的类函数ntohl()把网络字节序转换成长整形主机字节序.
#函数中的n表示网络;h表示主机;l表示长整形;s表示短整形,即16位
import socket
data=1
socket.ntohl(data)
socket.htonl(data)
socket.ntohs(data)
socket.htons(data)
------------------------------------------------------------------------------
#1.7设定并获取默认的套接字超时时间
import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.gettimeout()
s.settimeout(100)
s.gettimeout()
s.settimeout(None)
s.gettimeout()
------------------------------------------------------------------------------
#1.8优雅地处理套接字错误
#1_7_socket_errors.py
------------------------------1.8start
import sys
import socket
import argparse
def main():
#setup argument parsing
parser=argparse.ArgumentParser(description='Socket Error Examples')
parser.add_argument('--host',action="store",dest="host",required=False)
parser.add_argument('--port',action="store",dest="port",type=int,required=False)
parser.add_argument('--file',action="store",dest="file",required=False)
given_args=parser.parse_args()
host=given_args.host
port=given_args.port
filename=given_args.file
#First try-except block --create socket
try:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error,e:
print "Error creating socket:%s"%e
sys.exit(1)
#Second try-except block --connnect to given host/port
try:
s.connect((host,port))
except socket.gaierror,e:
print "Address-related error connecting to server:%s"%e
sys.exit(1)
except socket.error,e:
print "Connection error:%s"%e
sys.exit(1)
#Third try-except block -- sending data
try:
s.sendall("GET %s HTTP/1.0\r\n\r\n"%filename)
except socket.error,e:
print "Error sending data:%s"%e
sys.exit(1)
while 1:
#Fourth try-except block--waiting to receive data from remote host
try:
buf=s.recv(2048)
except socket.error,e:
print "Error receiving data:%s"%e
sys.exit(1)
if not len(buf):
print buf
break
#write the received data
sys.stdout.write(buf)
if __name__=='__main__':
main()
------------------------------1.8end
------------------------------------------------------------------------------
#1.9修改套接字发送和接收的缓冲区大小
import socket
SEND_BUF_SIZE=4096
RECV_BUF_SIZE=4096
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
bufsize=sock.getsockopt(socket.SOL_SOCKET,socket.SO_SNDBUF)
print "Buffer size [Before]:%d"%bufsize
sock.setsockopt(socket.SOL_TCP,socket.TCP_NODELAY,1)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_SNDBUF,SEND_BUF_SIZE)
sock.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,RECV_BUF_SIZE)
bufsize=sock.getsockopt(socket.SOL_SOCKET,socket.SO_SNDBUF)
print "Buffer size [After]:%d"%bufsize
------------------------------------------------------------------------------
#1.10把套接字改成阻塞或非阻塞模式
#1_9_socket_modes.py
import socket
def test_socket_modes():
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setblocking(1)
s.settimeout(0.5)
s.bind("127.0.0.1",0))
socket_address=s.getsockname()
print "Trivial Server launched on socket:%s"%str(socket_address)
while(1):
s.listen(1)
if __name__=='__main__':
test_socket_modes()
------------------------------------------------------------------------------
#1.11重用套接字地址
#1_10_reuse_socket_address.py
------------------------------1.11start
#1_10_reuse_socket_address.py
import socket
import sys
def reuse_socket_addr():
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
old_state=sock.getsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR)
print "Old sock state:%s"%old_state
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
new_state=sock.getsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR)
print "New sock state:%s"%new_state
local_port=8282
srv=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
srv.bind(('',local_port))
srv.listen(1)
print("Listening on port:%s"%local_port)
while True:
try:
connection,addr=srv.accept()
print "Connected by %s:%s"%(addr[0],addr[1])
except KeyboardInterrupt:
break
except socket.error,msg:
print '%s'%(msg,)
if __name__=='__main__':
reuse_socket_addr()
------------------------------1.11end