python socket 服务:ipv4、ipv6

1,502次阅读
没有评论

基本

  • 判断是ipv4、ipv6
class IPvStatus():

    def __init__(self, ip):
        self.ip = ip
    def ipv4(self):
        try:
            socket.inet_pton(socket.AF_INET, self.ip)
        except AttributeError:
            try:
                socket.inet_aton(self.ip)
            except socket.error:
                return False
            return self.ip.count('.') == 3
        except socket.error:
            return False
        return True

    def ipv6(self):
        try:
            socket.inet_pton(socket.AF_INET6, self.ip)
        except socket.error:
            return False
        return True
    
    def is_ip(self): # 是否是ip
        if self.ipv4() or self.ipv6():
            return True
        else:
            return False

客户端

import json
import struct

host = "127.0.0.1"
ip_status = IPvStatus(host)
if ip_status.ipv6():
    # ipv6
    mySocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
    port = 4256
else:
    # ipv4
    mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    port = 5506
try:
    mySocket.connect((host, port))
except:
    pass
dic_data = {}
# 数据总长度
size = len(json.dumps(dic_data).encode("utf-8"))
# 模拟报头
f = struct.pack("l", size)
# 先发送报头
mySocket.send(f)
# 再发数据
mySocket.send(json.dumps(dic_data).encode("utf-8"))
msg = mySocket.recv(10240)
if msg:
    msg = json.loads(str(msg, encoding="utf-8"))
    mySocket.close()
else:
    mySocket.close()

服务端

  • ipv4
import socket
import json
import struct

# 创建套接字
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置IP和端口
host = '0.0.0.0'
port = 5506
block_size = 512
recv_data_size = 0
# bind绑定该端口
mySocket.bind((host, port))
# 监听
mySocket.listen(10)
while True:
    client, address = mySocket.accept()
    while True:
        # 接受定长报头
        data_header = client.recv(struct.calcsize("l"))
        total_size = struct.unpack("l", data_header)
        # 真正数据总长度
        size = total_size[0]
        data_bytes = b''
        while recv_data_size < size:
            data = client.recv(block_size)
            data_bytes += data
            recv_data_size += len(data)
        if data_bytes:
            data_dic = str(data_bytes, encoding='utf-8')
            # 真实数据
            data_dic = json.loads(data_dic)
        break
  • ipv6
import socket
import json
import struct

# 创建套接字
mySocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
# 设置IP和端口
host = ''
port = 4256
block_size = 512
recv_data_size = 0
# bind绑定该端口
mySocket.bind((host, port))
# 监听
mySocket.listen(10)
while True:
    client, address = mySocket.accept()
    while True:
        # 接受定长报头
        data_header = client.recv(struct.calcsize("l"))
        total_size = struct.unpack("l", data_header)
        # 真正数据总长度
        size = total_size[0]
        data_bytes = b''
        while recv_data_size < size:
            data = client.recv(block_size)
            data_bytes += data
            recv_data_size += len(data)
        if data_bytes:
            data_dic = str(data_bytes, encoding='utf-8')
            # 真实数据
            data_dic = json.loads(data_dic)
        break

注意:

​ ipv6服务端的host绑定空字符串

  • 优化完整代码
import socket
import json
import struct


class SocketMain():
    def __init__(self, ipv4_port=5506, ipv6_port=4256, block_size=512, host=None, port=None):
        self.ipv4_host = "127.0.0.1"
        self.ipv6_host = ""
        self.ipv4_port = ipv4_port
        self.ipv6_port = ipv6_port
        self.block_size = block_size
        self.recv_data_size = 0
        self.host = host
        self.port = port
		# 服务端
    def socket_server(self, is_ipv4=True):
        if is_ipv4:
            host = self.ipv4_host
            port = self.ipv4_port
            mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            host = self.ipv6_host
            port = self.ipv6_port
            mySocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        mySocket.bind((host, port))
        # 监听
        mySocket.listen(10)
        while True:
            client, address = mySocket.accept()
            while True:
                # 接受定长报头
                data_header = client.recv(struct.calcsize("l"))
                total_size = struct.unpack("l", data_header)
                # 真正数据总长度
                size = total_size[0]
                data_bytes = b''
                while self.recv_data_size < size:
                    data = client.recv(self.block_size)
                    data_bytes += data
                    self.recv_data_size += len(data)
                if data_bytes:
                    data_dic = str(data_bytes, encoding='utf-8')
                    # 真实数据
                    data_dic = json.loads(data_dic)
                    if data_dic:
                        return data_dic
                break
		# 客户端
    def Socket_client(self):
        if not (self.host and self.host):
            return False
        ip_status = IPvStatus(self.host)
        if ip_status.ipv6():
            # ipv6
            mySocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            port = 4256
        else:
            # ipv4
            mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            port = 5506
        try:
            mySocket.connect((self.host, port))
        except:
            pass
        dic_data = {}
        # 数据总长度
        size = len(json.dumps(dic_data).encode("utf-8"))
        # 模拟报头
        f = struct.pack("l", size)
        # 先发送报头
        mySocket.send(f)
        # 再发数据
        mySocket.send(json.dumps(dic_data).encode("utf-8"))
        msg = mySocket.recv(self.block_size)
        if msg:
            msg = json.loads(str(msg, encoding="utf-8"))
            mySocket.close()
        else:
            mySocket.close()
正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 0
评论(没有评论)

文心AIGC

2024 年 4 月
1234567
891011121314
15161718192021
22232425262728
2930  
文心AIGC
文心AIGC
人工智能ChatGPT,AIGC指利用人工智能技术来生成内容,其中包括文字、语音、代码、图像、视频、机器人动作等等。被认为是继PGC、UGC之后的新型内容创作方式。AIGC作为元宇宙的新方向,近几年迭代速度呈现指数级爆发,谷歌、Meta、百度等平台型巨头持续布局
文章搜索
热门文章
清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开 Jay 2026-01-08 20:18:...
训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享 衡宇 2026-01-08 20:...
手把手教你用AI 10分钟生成一个APP!零基础也能搞定

手把手教你用AI 10分钟生成一个APP!零基础也能搞定

今日,我将向大家展示DeepSeek的全新玩法——从零开始,利用AI创建一个完整的应用程序。借助DeepSee...
开源“裸考”真实世界,国产具身智能基座模型拿下全球第二!

开源“裸考”真实世界,国产具身智能基座模型拿下全球第二!

开源“裸考”真实世界,国产具身智能基座模型拿下全球第二! 西风 2026-01-08 19:02:20 来源:...
最新评论
ufabet ufabet มีเกมให้เลือกเล่นมากมาย: เกมเดิมพันหลากหลาย ครบทุกค่ายดัง
tornado crypto mixer tornado crypto mixer Discover the power of privacy with TornadoCash! Learn how this decentralized mixer ensures your transactions remain confidential.
ดูบอลสด ดูบอลสด Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
Obrazy Sztuka Nowoczesna Obrazy Sztuka Nowoczesna Thank you for this wonderful contribution to the topic. Your ability to explain complex ideas simply is admirable.
ufabet ufabet Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
ufabet ufabet You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
ufabet ufabet Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
热评文章
8块钱跑通一次强化学习全流程,潞晨云重塑微调赛道:1名算法工程师=1支Infra团队

8块钱跑通一次强化学习全流程,潞晨云重塑微调赛道:1名算法工程师=1支Infra团队

8块钱跑通一次强化学习全流程,潞晨云重塑微调赛道:1名算法工程师=1支Infra团队 思邈 2026-01-0...
手把手教你用AI 10分钟生成一个APP!零基础也能搞定

手把手教你用AI 10分钟生成一个APP!零基础也能搞定

今日,我将向大家展示DeepSeek的全新玩法——从零开始,利用AI创建一个完整的应用程序。借助DeepSee...
清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开 Jay 2026-01-08 20:18:...
训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享 衡宇 2026-01-08 20:...