Skip to content

Commit

Permalink
socket_extra: created isIP to check if value is IP or not.
Browse files Browse the repository at this point in the history
  • Loading branch information
YoSTEALTH committed Jul 12, 2024
1 parent 361af20 commit 69b970d
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/liburing/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from dynamic_import import importer


__version__ = '2024.7.10'
__version__ = '2024.7.12'


importer(exclude_dir=['lib', 'include'])
Expand Down
1 change: 1 addition & 0 deletions src/liburing/socket_extra.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ cpdef int getpeername(int sockfd, sockaddr addr) nogil
cpdef tuple[bytes, uint16_t] getsockname(int sockfd, sockaddr addr)

cpdef tuple getnameinfo(sockaddr addr, int flags=?)
cpdef bint isIP(sa_family_t family, char* value) noexcept nogil

cpdef enum __extra_define__:
# getaddrinfo/getnameinfo start >>>
Expand Down
30 changes: 28 additions & 2 deletions src/liburing/socket_extra.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ cdef class getaddrinfo:
'''
# TODO: `port_service` should handle both `int` & `bytes` types.
cdef:
int no
__addrinfo hints
int no
__addrinfo hints

memset(&hints, 0, sizeof(__addrinfo))
hints.ai_flags = flags
Expand Down Expand Up @@ -123,3 +123,29 @@ cpdef tuple getnameinfo(sockaddr addr, int flags=0):
trap_error(__getnameinfo(<__sockaddr*>addr.ptr, addr.sizeof,
host, sizeof(host), service, sizeof(service), flags))
return (host, int(service) if service.isdigit() else service)


cpdef bint isIP(sa_family_t family, char* value) noexcept nogil:
'''
Example
>>> isIP(AF_INET, b'0.0.0.0')
True
>>> isIP(AF_INET6, b'::1')
True
>>> isIP(AF_INET6, b'domain.ext')
False
>>> isIP(AF_INET, b'domain.ext')
False
>>> isIP(AF_UNIX, b'/path/socket')
False
'''
cdef:
__sockaddr_in ptr_in
__sockaddr_in6 ptr_in6

if family == __AF_INET:
return __inet_pton(family, value, &ptr_in.sin_addr)
elif family == __AF_INET6:
return __inet_pton(family, value, &ptr_in6.sin6_addr)
else:
return False
9 changes: 9 additions & 0 deletions test/socket/socket_extra_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import liburing


def test_isIP():
assert liburing.isIP(liburing.AF_INET, b'0.0.0.0') is True
assert liburing.isIP(liburing.AF_INET6, b'::1') is True
assert liburing.isIP(liburing.AF_INET6, b'domain.ext') is False
assert liburing.isIP(liburing.AF_INET, b'domain.ext') is False
assert liburing.isIP(liburing.AF_UNIX, b'/path/socket') is False

0 comments on commit 69b970d

Please sign in to comment.