Skip to content

Commit

Permalink
nlsocket: fix bind() port
Browse files Browse the repository at this point in the history
  • Loading branch information
svinota committed Dec 16, 2024
1 parent 9aa4596 commit 1e697ea
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 14 deletions.
8 changes: 0 additions & 8 deletions pyroute2/netlink/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,14 +218,6 @@ def set_marshal(self, value):
def msg_queue(self):
return self.local.msg_queue

@property
def port(self):
if not hasattr(self.local, 'port'):
import random

self.local.port = random.randint(20, 200)
return self.status['pid'] + (self.local.port << 22)

@property
def connection_lost(self):
return self.local.connection_lost
Expand Down
23 changes: 17 additions & 6 deletions pyroute2/netlink/nlsocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,14 @@ def groups(self):
def pid(self):
return self.status['pid']

@property
def port(self):
return self.status['port']

@property
def epid(self):
return self.status['epid']

@property
def target(self):
return self.status['target']
Expand Down Expand Up @@ -307,13 +315,16 @@ async def bind(self, groups=0, pid=None, **kwarg):
- If pid == <int>, use the value instead of pid
'''
await self.ensure_socket()
self.status['groups'] = groups
self.spec['groups'] = groups
# if we have pre-defined port, use it strictly
self.status['pid'] = pid
self.spec['pid'] = pid
if pid is None:
for port in range(1024):
for port in range(20, 200):
try:
self.socket.bind((self.port, self.status['groups']))
self.spec['port'] = port
self.socket.bind(
(self.status['epid'], self.status['groups'])
)
break
except Exception as e:
# create a new underlying socket -- on kernel 4
Expand Down Expand Up @@ -435,7 +446,7 @@ def __init__(
self.sock = sock
self.addr_pool = sock.addr_pool
self.status = sock.status
self.port = sock.port if msg_pid is None else msg_pid
self.epid = sock.epid if msg_pid is None else msg_pid
self.marshal = sock.marshal
self.parser = parser
# if not isinstance(msg, nlmsg):
Expand All @@ -449,7 +460,7 @@ def __init__(
msg['header']['type'] = msg_type
msg['header']['flags'] = msg_flags
msg['header']['sequence_number'] = self.msg_seq
msg['header']['pid'] = self.port or os.getpid()
msg['header']['pid'] = self.epid or os.getpid()
msg.reset()
# set fields
if request_filter is not None:
Expand Down

0 comments on commit 1e697ea

Please sign in to comment.