Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to obtain socket domain of not connected, nor binded socket

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading