getsockname() returns invalid-looking name

235 Views Asked by At

I'm new to socket programming. Having created a socket pair with socketpair(), I wanted to investigate what address the sockets are bound to. But when I try to determine this with getsockname(), I get an invalid-looking result.

The code:

#include <iostream>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdint.h>

int identifysock( int sd )
{
  std::ios_base::fmtflags mask = std::cout.flags();
  int ret_val = 0;
  std::cout << " === SD " << sd << " ===" << std::endl;
  struct sockaddr_un su;
  socklen_t addrlen = sizeof( sockaddr_un );
  std::cout << "before getsockname() addrlen == " << addrlen << std::endl;
  memset( &su, 0, sizeof( sockaddr_un ) );
  if ( getsockname( sd, (sockaddr*)&su, &addrlen ) )
  {
    std::cout << "Error" << std::endl;
    ret_val = 1;
  }
  else
  {
    std::cout << "after getsockname() addrlen == " << addrlen << " name == " << su.sun_path << std::endl;
    std::cout << std::showbase << std::hex << (uint32_t)su.sun_path[0] << " " << (uint32_t)su.sun_path[1] << std::endl;
  }
  std::cout.flags(mask);
  return ret_val;
}

int main( int argc, char* argv[] )
{
  int sd[2];
  if ( socketpair( AF_LOCAL, SOCK_STREAM, 0, sd ) )
  {
    std::cout << "Error" << std::endl;
    return 1;
  }
  std::cout << "sd[ 0 ] == " << sd[ 0 ] << std::endl;
  std::cout << "sd[ 1 ] == " << sd[ 1 ] << std::endl;
  if ( identifysock( sd[ 0 ] ) )
  {
    return 1;
  }
  if ( identifysock( sd[ 1 ] ) )
  {
    return 1;
  }
  return 0;
}

The output:

>g++ -g main.cpp
>./a.out
sd[ 0 ] == 3
sd[ 1 ] == 4
 === SD 3 ===
before getsockname() addrlen == 110
after getsockname() addrlen == 2 name == 
0 0
 === SD 4 ===
before getsockname() addrlen == 110
after getsockname() addrlen == 2 name == 
0 0

Per my understanding, getsockname() is telling me there should be an address of length 2. But the two bytes starting at su.sun_path are 0 - surely this cannot be a valid address can it?

I know that socketpair() creates a pair of "unnamed" sockets - but I thought an "unnamed socket" just meant an abstract namespace, that was still some unique, non-NULL string thereof.

Can someone explain why this code outputs the observed invalid-looking namespace?

0

There are 0 best solutions below