views:

83

answers:

4
+1  Q: 

client port number

I was wondering how to, using C, find out what port a client is currently listening to. ie, I want to know what the source port is, not the destination port.

Thanks in advance!

A: 

Not sure what you mean. Clients don't listen, servers do.

Meta
I thought they listen to an open port number that they query the OS for. It seems to be the case... also, for some reason, torrent servers require you to send the port the client is listening on.
Cenoc
@Cenoc: that's because a bittorrent client also acts as a "server" for other machines in the swarm to connect to (i.e., it receives incoming connections). P2P confuses the usual client-server division, but when talking about a single TCP connection, saying "client" implies whoever initiated the connection.
Steve Jessop
Right, but it still connects as a client, so my question is, how would I find that source port to send in that scenario?
Cenoc
It will be buried in your bittorrent client's options somewhere. Options > Preferences > Connection in the mainline client. If you're asking how the bittorrent code knows what port to send, then either it picks one for itself (in which case it knows what it picked), or else it can call `getsockname()` once the socket is bound.
Steve Jessop
Well I meant how would I set it (the port number) using C or find out which port number is the source port without going into the raw. I'm not writing a bittorrent, but I was wondering how this could be done using C...
Cenoc
Sorry, it's part of the `sockaddr_in` structure ("in" meaning "internet"), which is used wherever a Berkely-style sockets API mentions a `struct sockaddr*`. So normally when you call `bind`, you specify the port then, and that's what port will be listened on when you call `listen`.
Steve Jessop
I dont know how to give you the answer, I'll just give you a 1up. Thanks a lot though.
Cenoc
A: 

If you're talking about how to scan for all open ports, then you might be after a port scanner. There are many many many many source codes available but I definitely don't recommend you use one of them, they are usually slow even if multithreading is enabled. Why? There's nmap : http://nmap.org/

Ruel
A: 

The socket address structure should be filled-in by the connect() system-call. Check it after a successful return from that call.

Steve Emmerson
Steve Jessop gave me the answer I was looking for, Im not sure what to do with this question now...
Cenoc
A: 

Depending on what you want (which I'm too obtuse to guess right now), you want to call either getsockname() or getpeername().

ninjalj