首页 > 代码库 > 1套接字IP4和简单的客户服务端
1套接字IP4和简单的客户服务端
#coding=utf-8
import socket
print socket.gethostname() #获取主机名
print socket.gethostbyname(socket.gethostname()) #获取IP地址
try:
print socket.gethostbyname(‘www.163.com‘) #获取远程地址IP
except Exception, e:
raise e
客户端:one_client.py
#coding=utf-8 import socket import sys import argparse host = ‘localhost‘ def echo_client(port,d): #创建IP/tcp连接 sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_address =(host,port) sock.connect(server_address) try: sock.sendall(d) amount_r = 0 amount_e = len(d) while amount_r<amount_e: data=http://www.mamicode.com/ sock.recv(16)>服务端:one_server.py
#coding=utf-8 import socket import sys import argparse host = ‘localhost‘ data_payload=2048 backlog=5 def echo_server(port): #创建TCP连接 sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #启用 地址端口 sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #绑定端口 server_address = (host,port) print "Starting up echo server on %s port %s"%server_address sock.bind(server_address) sock.listen(backlog) while True: # print ‘waiting to receive message form client‘ client,address = sock.accept() data = client.recv(data_payload) if data: print "Data:%s"%data client.send(data) # print "send %s bytes back to %s"%(data,address) client.close() if __name__=="__main__": parser = argparse.ArgumentParser(description=‘Socket Server Example‘) parser.add_argument(‘-p‘,action=‘store‘,dest=‘port‘,type=int,required=True) given_atgs=parser.parse_args() post=given_atgs.port echo_server(post)本文出自 “anaf” 博客,谢绝转载!
1套接字IP4和简单的客户服务端
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。