Mbded
Mbded

Reputation: 1916

How to get local port not knowing socket

My program works as client some outside service. I want to get local port using by my program. It wasn't problem when I had handle to socket, then probably I will use this way:

Get Local Port used by Socket

But I don't get handle to socket because socket is created somewhere in shared library provided by some company (I not have source only *.so). I have only function to create connection with some service with random port, and function to use this service, nothing more. So when I created connection I don't know what port choose system, but I would to know that after in my program.

#include "somesharedlibrary.h"

int main(int argc, char *argv[])
{

    // some uid , 0 means choose random port (must be), user, password
    int i = CreateConnectionToSecretService("38324f42" , 0  , "admin" , "admin");
    if (i != 0){
        printf("Ok I have connection from service");
        // Now I have connection let's say on 0.0.0.0.:1234
        // I know that using netstat- antl, but of course
        // I don't know that in code. Therefore my question for You.
        // It is posible get local port which was used by system in this place ?
    }else{
        printf("something is wrong by.. by..")
    }

        return 0;
}

SOLVED

As said SergeyA after long discussions :). When My Program was connected to service were created 2 new file descriptor: for UDP, and TCP connection. For TCP is descriptor nr 4. Then enought write below code:

struct sockaddr_in foo;
socklen_t len = sizeof foo;
int f = getsockname(4, (struct sockaddr *)&foo, &len );
printf( "%s", inet_ntoa( foo.sin_addr));

Thanks

Upvotes: 2

Views: 464

Answers (1)

SergeyA
SergeyA

Reputation: 62553

Since you mention .so, I take it is some of the *Nix variant. And since it is *nix, it means it is Linux :)

It is rather easy to do this. Just take a snapshot of process file descriptors before calling create connection - for instance, by reading /proc//fd - and than after calling connection. The extra descriptor you see there would be a new socket opened (if there is more than one, it means, library opened more than one descriptor - you will have to guess which is the one you need.) Now you have your descriptor and you can inquiry it.

Upvotes: 4

Related Questions