This commit adds a new function get_random_port to return a randomly
available port from the local port range.
Change-Id: Icaed180cc14602a74cdb3fd3456b690d8a4c729c
... | ... |
@@ -732,6 +732,24 @@ function set_systemd_override { |
732 | 732 |
sudo systemctl daemon-reload |
733 | 733 |
} |
734 | 734 |
|
735 |
+# Get a random port from the local port range |
|
736 |
+# |
|
737 |
+# This function returns an available port in the local port range. The search |
|
738 |
+# order is not truly random, but should be considered a random value by the |
|
739 |
+# user because it depends on the state of your local system. |
|
740 |
+function get_random_port { |
|
741 |
+ read lower_port upper_port < /proc/sys/net/ipv4/ip_local_port_range |
|
742 |
+ while true; do |
|
743 |
+ for (( port = upper_port ; port >= lower_port ; port-- )); do |
|
744 |
+ sudo lsof -i ":$port" &> /dev/null |
|
745 |
+ if [[ $? > 0 ]] ; then |
|
746 |
+ break 2 |
|
747 |
+ fi |
|
748 |
+ done |
|
749 |
+ done |
|
750 |
+ echo $port |
|
751 |
+} |
|
752 |
+ |
|
735 | 753 |
|
736 | 754 |
# Restore xtrace |
737 | 755 |
$_XTRACE_FUNCTIONS |