Solved

Linux: get socket source port used after connect()

Posted on 2008-06-21
2
3,288 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

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

The purpose of this article is to fix the unknown display problem in Linux Mint operating system. After installing the OS if you see Display monitor is not recognized then we can install "MESA" utilities to fix this problem or we can install additio…
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…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Finding and deleting duplicate (picture) files can be a time consuming task. My wife and I, our three kids and their families all share one dilemma: Managing our pictures. Between desktops, laptops, phones, tablets, and cameras; over the last decade…

739 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