Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Byte-compiled / optimized / DLL files
__pycache__/
.idea/
*.py[cod]
*$py.class

Expand Down
49 changes: 49 additions & 0 deletions lightsocks/utils/addr_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# coding:utf-8
"""
Check the availability of IP and port.
Author: kerbalwzy@gmail.com
Date: 2019-07-08
"""

import socket


def _host_addresses() -> set:
"""
Get the all addresses of the host, just include IPV4
:return: address
"""
address = socket.getaddrinfo(socket.gethostname(), None)
address = [item[4][0] for item in address if ':' not in item[4][0]]
address.extend(["127.0.0.1", "0.0.0.0"])
return set(address)


def ip_validate(ip: str) -> bool:
"""
The ip is require be one of the host addresses
:param ip: string, the ip need to be check
:return: boolean value
"""
return ip in _host_addresses()


def _port_is_free(port: int) -> bool:
"""
Try connect a local port. If success meanings the port is using.
:param port: int, the port need be check.
:return: boolean value.
"""
with socket.socket() as s:
s.settimeout(0.5)
# s.connect_ex return 0 means port is open and using
return s.connect_ex(('localhost', port)) != 0


def port_validate(port: int) -> bool:
"""
The port is required in range 1024 to 65535, and spare.
:param port: int, the port need be check
:return: boolean value
"""
return 1023 < port < 65536 and _port_is_free(port)
3 changes: 1 addition & 2 deletions lightsocks/utils/net.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from collections import namedtuple


Address = namedtuple('Address', 'ip port')
Address = namedtuple('Address', 'ip port')
22 changes: 22 additions & 0 deletions lightsocks/utils/test_addr_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# coding:utf-8
"""
Check the availability of IP and port.
Author: kerbalwzy@gmail.com
Date: 2019-07-08
Note: 单元测试运行会把 "函数注解" 识别为语法错误,如果你要运行,请先在代码中删除函数注解
"""

import unittest
from lightsocks.utils.addr_check import ip_validate, port_validate


class UtilsAddrCheckTest(unittest.TestCase):
def test_ip_validate(self):
self.assertTrue(ip_validate("127.0.0.1"))
self.assertTrue(ip_validate("0.0.0.0"))
self.assertFalse(ip_validate("abc"))
self.assertFalse(ip_validate("127.0.0.256"))

def test_port_validate(self):
self.assertFalse(port_validate(22))
self.assertFalse(port_validate(1023))