Is there a portable way for a running process to discover what
local port number has been allocated by the kernel to a socket?
I don't believe using netstat is portable since it looks up the
/proc file system which seems to differ between unices.
For the server side of a socket connection one can look at the value
in sin_port of the sockaddr structure. However for the client side,
where this is set to the server side port number to make the correct
connection to the server, it is this (remote) port number which is held
in sin_port rather than the local port number.
Any ideas?
chris
--
Chris Willing Ph: (61-2) 9351 1893 (| 3005)
Vislab, A28 Fax: (61-2) 9351 1880 (| 7726)
University of Sydney Email: ch...@vislab.usyd.edu.au
NSW 2006 Australia http://www.vislab.usyd.edu.au/staff/chris/
> Is there a portable way for a running process to discover what
> local port number has been allocated by the kernel to a socket?
lsof would do it.
> I don't believe using netstat is portable since it looks up the
> /proc file system which seems to differ between unices.
Oh, you're worried about _portability_. Oh. In that case, netstat is
portable, but not in the sense you mean. You can system("netstat"... and
expect it to be portable, but you can not lift the netstat code, stick it
in your app and expect it to be portable.
As for an honest-to-god answer to this problem, I'm clueless, as normal.
--
Todd Graham Lewis Linux! Core Engineering
MindSpring Enterprises tle...@mindspring.net (800) 719 4664, x2804
After a bit of fiddling I can now answer my own question.
It is true that the sin_port field is initially set to the remote
port number e.g. 21 for an ftp connection. To find the local
port number it is necessary to call
getsockname(sockNo, (struct sockaddr *)&sin, &sin_len)
after the connection is made (where sin is the name of the struct sockaddr_in).
By this time sin_port contains the local port number so,
localPort = ntohs(sin.sin_port);
gives the desired result.
OK, I'll fiddle a bit more before I next ask a question.