Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c++ - casting between sockaddr and sockaddr_in

I came across a socket programming tutorial in which it is quoted

"a pointer to a struct sockaddr_in can be cast to a pointer to a struct sockaddr and vice-versa"

I dont understand how can sockaddr_in be cast to sockaddr. Casting a pointer of Big type to Small type should give UD behavior.

struct sockaddr {
unsigned short sa_family; // address family, AF_xxx
char sa_data[14]; // 14 bytes of protocol address
};


struct sockaddr_in {
short int sin_family; // Address family, AF_INET
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
unsigned char sin_zero[8]; // Same size as struct sockaddr
};

How can the cast not be undefined? Isn't it unsafe to cast these to each other?

If i have a class A having only two ints and class B having 4 ints. And if i have a pointer of type B and i cast it to type A then sure i can fetch the first two elements. But if class A has 2 chars declared first and 2 ints declared later then the pointers would not right fetch the values since the object layout in this case would be different.

Edit 1:

class Anu
{
public:
    char a;
    int b;
    Anu()
    {
        a='a';
    }
};
class Anurag
{
public:
    Anurag() { a=4;}
    int a;
    int b;
    int c;
    int d;
};
int main()
{
        Anu objanu;
        Anurag objanurag;
        Anurag *ptrAnurag= &objanurag;
        ptrAnurag= (Anurag*)&objanu;
        cout<<ptrAnurag->a; //Some weird value here
        return 0;
}

Assuming i change the example so that both classes have same size by adjusting the variables types...still the object layout might be different even though the size remains the same.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'll add to @gsamaras answer by saying that Undefined Behaviour doesn't always means that bad things are about to happen. Undefined Behaviour actually says "we* don't provide any specifications on what should happen next if XYZ occurs".

(*the C++ standard).

this is the place where the OS takes place and say "it is defined by us".

although casting unrelated structs (sockaddr_in,sockaddr) may be undefined behaviour by the standard, the OS API specify that it is valid with their API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...