Search code examples
csocketsstructposixtcp

Typecasting structures with different definitions


I came across this in socket programming:

struct sockaddr {
    sa_family_t sa_family;
    char        sa_data[14];
}

struct sockaddr_in {
    sa_family_t    sin_family; /* address family: AF_INET */
    in_port_t      sin_port;   /* port in network byte order */
    struct in_addr sin_addr;   /* internet address */
};

These are the two structures with different type and this is how I was made to use them

Client Side:

connect(sfd,(struct sockaddr *)&caddr,clen; //type casted one

Server Side:

bind(sfd,(struct sockaddr *)&saddr,slen);
accept(sfd,(struct sockaddr *)&caddr,&clen);

Here structures with different definitions are being type casted how does this affects the variable?

Even though I typecast I can access the variables like this:

printf("File Descriptor : %d\n", fd);
char *p = inet_ntoa(caddr.sin_addr);
unsigned short port_no = ntohs(caddr.sin_port);

printf("Ip address : %s\n", p);
printf("Ephimeral port : %d\n", port_no);

What is the use of this kind of typecasting? Even though I have have typecasted it how can I access those members of other structures (addr_in here)? I want to know how these operations take place and understand the need for typecasting different structures.


Solution

  • The perfect term will be "type punning" instead of calling it as typecasting.

    sockaddr_in is for IP based communication in which we specify type of protocol, IP addr, port etc and sockaddr is a generic struct used in socket operation. The bind() uses sockaddr thus type punning is required.

    You can search for type punning and can get more information.