Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill sockaddr_storage?

Tags:

c++

sockets

I am trying to use sockaddr_storage struct in my application. I am curious how to fill it. For example I have following code:

sHostAddr.sin_family = AF_INET;
sHostAddr.sin_addr.s_addr = inet_addr (cpIPAddress);

How can I replace it if I use sockaddr_storage struct? I know that there are some char arrays, and I suppose I can get an equivalent code using some array index offsets?

Thanks on advance.

like image 423
unresolved_external Avatar asked Feb 19 '14 14:02

unresolved_external


2 Answers

The name is the hint, sockaddr_storage is for storage only, not for accessing. Use in a union with specific protocol structures:

union {
  struct sockaddr         sa;
  struct sockaddr_in      s4;
  struct sockaddr_in6     s6;
  struct sockaddr_storage ss;
} addr;
memset (&addr.s4, 0, sizeof(struct sockaddr_in));
addr.s4.sin_family = AF_INET;
addr.s4.sin_addr.s_addr = INADDR_ANY;

or memcpy, e.g.

struct sockaddr_storage storage;
struct sockaddr_in sin;

memset (&sin, 0, sizeof (sin));
sin.sin_family = AF_INET
sin.sin_addr.s_addr = inet_addr ("127.0.0.1");
memcpy (&storage, &sin, sizeof (sin));
like image 199
Steve-o Avatar answered Nov 10 '22 06:11

Steve-o


You need to cast it. If for example your sin_family is AF_INET6, you can cast the sockaddr_storage pointer to a sockaddr_in6 pointer and then fill in whatever you need to.

It is just a general socket address holding structure, big enough to hold either struct sockaddr_in or struct sockaddr_in6 data or any future sockaddr_xxx..

You can find one example usage here: http://www.kame.net/newsletter/19980604/

Note that sometimes developers will redefine this structure to use a union instead. That can have some side effects and isn't cross-platform.

like image 40
Brandon Avatar answered Nov 10 '22 04:11

Brandon