[Python network programming]socket simple Use (i)

Source: Internet
Author: User
Tags connect socket

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.