【学习笔记】python 简单创建新建一个网络客户端,并返回相关的信息

#导入socket包
import socket

#使用socket.socket创建socket连接
#AF_INET表示通信类型,与IPv4对应 
#SOCK_STREAM对应TCP通信
print('creating socket...')
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('done')

print('looking up port number..')
port=socket.getservbyname('http','tcp')
print('done')

#tuple
print('connecting to remote host on port %d...'%port)
s.connect(('www.baidu.com',port))
print('done')

#返回本地IP和端口号,返回远程机器IP和端口号
print(s.getsockname())
print(s.getpeername())
原文地址:https://www.cnblogs.com/test-xiaocai/p/5954942.html