# Specifying ports when creating sockets?

**URL:** <https://www.ruby-forum.com/t/specifying-ports-when-creating-sockets/169569>\
**Category:** Ruby\
**Created:** [June 5, 2009, 11:33am UTC](https://www.ruby-forum.com/t/specifying-ports-when-creating-sockets/169569 "2009-06-05T11:33:15Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexmic](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/977dab/32.png) [@alexmic](https://www.ruby-forum.com/u/alexmic)\
**Post date:** [June 5, 2009, 11:33am UTC](https://www.ruby-forum.com/t/specifying-ports-when-creating-sockets/169569/1 "2009-06-05T11:33:15Z")

</div>

In TCP, when you create a socket to a particular address, the OS chooses  
a free port number.

I’d like to either specify that port number, or find out that port  
number.

I can easily find the port number like so:  
socket.addr[1]

However, that fails when the IO stream is closed. I need to find out the  
port number even if the connection is never made. I’m not sure this is  
possible, which is why I think the first approach, specifying the port  
number, is the way to go.

If you’re wondering why I’m doing this, it’s to do with STUNT.

Can anybody provide any pointers?

---

<div class="post-metadata">

**Author:** ![alexmic](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/977dab/32.png) [@alexmic](https://www.ruby-forum.com/u/alexmic)\
**Post date:** [June 5, 2009, 11:50am UTC](https://www.ruby-forum.com/t/specifying-ports-when-creating-sockets/169569/2 "2009-06-05T11:50:18Z")

</div>

Alex M. wrote:

> In TCP, when you create a socket to a particular address, the OS chooses  
> a free port number.
> 
> I’d like to either specify that port number, or find out that port  
> number.
> 
> I can easily find the port number like so:  
> socket.addr[1]
> 
> However, that fails when the IO stream is closed. I need to find out the  
> port number even if the connection is never made. I’m not sure this is  
> possible, which is why I think the first approach, specifying the port  
> number, is the way to go.
> 
> If you’re wondering why I’m doing this, it’s to do with STUNT.
> 
> Can anybody provide any pointers?

Ok, somebody has kindly let me know that TCPSocket takes 4 options,  
including a local port - oops!

That should solve the issue.
