Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sockets Programming with Python: Get the port of a server [closed]

So as the title suggests is there any way that I can get the port of a website/ip with a socket connection? I assigned socket.gethostbyname() to the simple variable "ip" so that I can print out the result in console but can I do the same with the port? Here is the website that I am using to learn with > https://docs.python.org/3/library/socket.html < and what I am wondering is if this is a good source or does anyone know a better one? Thank you much :D

like image 914
IronReign Avatar asked Nov 29 '22 23:11

IronReign


1 Answers

You can get the currently used port with getsockname:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 0))
print('listening on port:', sock.getsockname()[1])
like image 108
Daniel Avatar answered Dec 05 '22 12:12

Daniel