一个简单的python代理服务器源码分析

本文介绍了一个简单的Python模块IPv4_Tools,用于验证IPv4地址是否可路由及端口号的有效性。提供了is_routable函数来判断IPv4地址是否符合RFC1918规定的不可路由范围,并通过is_port函数验证端口号是否在有效区间内。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

此为开源代码,可以google上下载,项目名为:PySocks-1.0a4

 

下面为其中文件之一的IPv4_Tools.py:

 

"""IPv4_Tools - IPv4 helper functions module written in Python

Copyright (C) 2001 Xavier Lagraula
See COPYRIGHT.txt and GPL.txt for copyrights information.

This module provides a small set of classes and short functions to ease for
IPv4 protocols handling:
- is_routable: checks whether an IP address is routable or not (RFC 1918).
- is_port: checks whether an integer is a valid port number (1-65535)
"""
   
def is_routable(address):
  """def is_routable(address)

This function returns if a given IPv4 address is routable or not.
Parameters:
- address: IPv4 address - string - format: aaa.bbb.ccc.ddd
Return value:
- 0: address is not routable
- 1: address is routable

Routable addresses are defined as not pertaining to the following:
127.0.0.0 - 127.255.255.255 (127/8 prefix)
10.0.0.0 - 10.255.255.255 (10/8 prefix)
172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
192.168.0.0 - 192.168.255.255 (192.168/16 prefix)"""

  # Splitting the address in its 4 components.
  first, second, junk1, junk2 = address.split('.')
  # Testing the address against the given intervals.
  if (first in ['10', '127']
  or (first == '172' and second >= '16' and second <= '31')
  or ((first, second) == ('192', '168'))):
  return 0
  return 1

def is_port(port):
  """def is_port(port)

This functions returns if a given port is valid or not.
Parameters:
- port: integer
Return value:
- 0: port is a valid port
- 1: port is not a valid port

Valid ports are defined as in the interval 1-65535."""
  return (port > 0) and (port < 65536)

注意两个"""之间的部分为注释,类似与C++中的/*和*/


除掉注释,此代码只有如下几行:

 

def is_routable(address):

    first, second, junk1, junk2 = address.split('.')

    if (first in ['10', '127']
        or (first == '172' and second >= '16' and second <= '31')
        or ((first, second) == ('192', '168'))):
        return 0
    return 1

 

def is_port(port):

    return (port > 0) and (port < 65536)

 

这几行代码很简单:函数is_routable主要是检测address是否可路由,声明四个变量分别得到IPv4地址的四个byte,然后判断各个byte是否符合要求,符合要求就返回1,否则返回0;函数is_port返回port是否为合格的端口号。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值