tags:

views:

24

answers:

3

This is the piece of the code I copied from one of the header file for socket programming.

/* Structure describing an Internet socket address.  */
struct sockaddr_in
  {
    __SOCKADDR_COMMON (sin_);
    in_port_t sin_port;                 /* Port number.  */
    struct in_addr sin_addr;            /* Internet address.  */

    /* Pad to size of `struct sockaddr'.  */
    unsigned char sin_zero[sizeof (struct sockaddr) -
                           __SOCKADDR_COMMON_SIZE -
                           sizeof (in_port_t) -
                           sizeof (struct in_addr)];
  };

I can understand declaration of sin_port and sin_addr. but what is __SOCKADDR_COMMON in_) is here. I can't understand this syntax? Kindly explain. Thanks in advance.

A: 

It is a macro defined somwhere else. It might be defined as

#define __SOCKADDR_COMMON(sa_prefix) \
  sa_family_t sa_prefix##family

expanding that, the struct would look like

struct sockaddr_in
  {
    sa_family_t sin_family;
    in_port_t sin_port;      
 ... 

DO NOT copy this structure into your code. You are supposed to include the header file for your system that declares struct sockaddr_in.

nos
What is this ## in second line?
It is the prerocessor token concatenation operator. See e.g. http://en.wikipedia.org/wiki/C_preprocessor#Token_concatenation
nos
A: 

__SOCKADDR_COMMON() will be a #define macro that expands a set of common fields to be used in all structures

Oli Charlesworth
+1  A: 

There exists the macro definition:

#define __SOCKADDR_COMMON(sa_prefix) \
  sa_family_t sa_prefix##family

so __SOCKADDR_COMMON (sin_); actually expands to sa_family_t sin_family;

The way this happens is that the macro takes the parameter sa_prefix and uses the ## operator to concatenate (join) them. The result is that you have a new variable sin_family which is declared with type sa_family_t in the struct.

Here's more info on macros and the C Preprocessor

jay.lee
i can't understand , what datatype sa_prefix and sin_? what actually they represent? And is __SOCKADDR_COMMON is a function?
answer expanded for comment
jay.lee
Thanks, I understood.