Solved

Linux: get socket source port used after connect()

Posted on 2008-06-21
2
3,282 Views
Last Modified: 2010-04-21
Hello, in Linux, how can I get the source port used by a socket after making a call to the connect system call? I want to save the source port used for later use.
Alternatively, how can I find out which source ports are not used, then I could just make a call to bind with that source port.

thanks
0
Comment
Question by:rocketsbay
2 Comments
 
LVL 34

Accepted Solution

by:
Duncan Roe earned 75 total points
ID: 21839437
Use getsockname() and cast the returned sockaddr to sockaddr_in. It then contains the port & IP.
getpeername() gets the remote port & IP.
To find an unused port, you have to call bind() on different ones until you don't get an error. Or you can call bind with a zero port and discover what port you got.
0
 

Author Closing Comment

by:rocketsbay
ID: 31469442
Thanks a lot, it`s exactly what I need.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
CentOS 6.6 Port opening question 1 137
Help with a backup script in Linux 4 76
Set-Top-Box hardware and Open Source! 8 310
BASH script to modify crontab? 3 92
Have you ever been frustrated by having to click seven times in order to retrieve a small bit of information from the web, always the same seven clicks, scrolling down and down until you reach your target? When you know the benefits of the command l…
The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question