Socket uses 1 socket basic parameters to understand
1. When setting up the socket object, you need to tell the system two things
1.1 What is the type of communication (Ipv4/ipv6, etc.)
1.2 What are the protocols used? (TCP/UDP, etc.)
2. Identification of individual communication types and protocols
2.1 Ipv4:af_inet
2.2 Ipv6:af_inet6
2.3 Tcp:sock_stream
2.4 Udp:sock_dgram
2 Socket Usage
1. Create a socket
# 创建一个socket,使用的通信类型是IPv4,使用的协议是TCP# socket.socket --> 创建一个socket连接s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
2. Connect the socket
# connect --> 连接# www.arppinging.com 代表地址,可以使用域名,python会解析得到地址之后再去连接,80为端口号,前面我们定义了SOCK_STREAM,所以这里使用的是TCP的80号端口s.connect(("www.arppinging.com",80))
Instance
1. Create a socket connection and abort immediately
#!/usr/bin/env python# basic Connection arppinging.com import socketprint "creating socket..."# 使用socket.socket创建一个sockets = socket.socket(socket.AF_INET,socket.SOCK_STREAM)print "done."print "Connecting to remote host......"# 使用connect连接sockets.connect(("www.arppinging.com",80))print "done."
Perform
2. Get socket Information
2.1 getsockname () IP and port number for this machine
2.2 Getpeername () Peer IP and port number
#!/usr/bin/env python# Information arppingingimport socketprint "Creating socket..."s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)print "done."print "Connect socket..."s.connect(("www.arppinging.com",80))print "done."# 获取本机的IP和portprint "Connected from",s.getsockname()# 获取对端的IP和portprint "Connected to",s.getpeername()
Run
Creating socket...done.Connect socket...done.Connected from (‘192.168.10.10‘, 44578)Connected to (‘119.28.23.106‘, 80)
[Python network programming]socket simple Use (i)