jdl
jdl

Reputation: 6323

Unable to get local host IP address from getsockname?

I am able to get the port returned, but the IP is not. Should I be using something else other than getsockname? thx

        if ((sock = ::socket(AF_INET, SOCK_STREAM, 0)) == -1) {
            c.Format("Socket Error:  %d", GetLastError());
            tcpMESSAGE = 1;
            break;
        }


        server_addr.sin_family = AF_INET;         
        server_addr.sin_port = htons(4000); //port setting    
        server_addr.sin_addr.s_addr = INADDR_ANY; 

        if (::bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) {
            c.Format("Bind Error:  %d", GetLastError());
            tcpMESSAGE = 1;
            break;
        }

        if(1==1){
            int len = sizeof server_addr;
            if(::getsockname(sock,(struct sockaddr*)&server_addr,&len) == -1)
                MessageBox("Error local host ip");

            c.Format("local addr %s:%u\n  errno: %d",inet_ntoa(server_addr.sin_addr),ntohs(server_addr.sin_port), errno);
            MessageBox(c);
        }

Upvotes: 0

Views: 3524

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596216

You are binding to INADDR_ANY, but you have not connected the socket to a peer yet, so there is no IP for getsockname() to return. After a connection has been established via connect() or accept(), then getsockname() can return the specific IP that is being used for that connection. Binding alone is not enough, unless you bind to a specific IP, which you are not doing.

Upvotes: 5

Related Questions