Home > front end >  How to obtain socket domain of not connected, nor binded socket
How to obtain socket domain of not connected, nor binded socket

Time:12-24

The title says it all. On Linux, how to know a domain of a not connected, nor binded socket.

Here is the code for reference.

#include <stdio.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
 int sd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0);
 int domain;
 socklen_t s_len; 

 if(sd < 0){
  perror("socket DID NOT create");
  return 1;
 }
 if(getsockopt(sd, SOL_SOCKET, SO_DOMAIN, &domain, &s_len) < 0){
  perror("getsockopt failed");
  return 2;
 }
 
 const char *so_domain = NULL;
 if(domain == AF_UNIX)
  so_domain = "AF_UNIX";

 printf("sock domain is: %d : %s\n", domain, so_domain);

 return 0;
}

The code returns zero for the domain.

CodePudding user response:

You are passing an uninitialised value of s_len to getsockopt(). From the manpage:

For getsockopt(), optlen is a value-result argument, initially containing the size of the buffer pointed to by optval, and modified on return to indicate the actual size of the value returned.

Changing it to:

 socklen_t s_len = sizeof domain; 

fixes it. Output:

sock domain is: 1 : AF_UNIX
  • Related