Casting von größerem Datentyp (Struktur) bis kleinerC++

Programme in C++. Entwicklerforum
Anonymous
 Casting von größerem Datentyp (Struktur) bis kleiner

Post by Anonymous »

Ich wusste bereits, dass Zeiger einer Struktur auf einen anderen Zeiger einer Struktur mit gleichwertigem Speicherlayout gegossen werden kann. < /p>

Im folgenden Code -Stück jedoch: < /p>

Code: Select all

#include 
#include 
#include 
#include 

#define MYPORT "3490"  // the port users will be connecting to
#define BACKLOG 10     // how many pending connections queue will hold

int main(void)
{
struct sockaddr_storage their_addr;
socklen_t addr_size;
struct addrinfo hints, *res;
int sockfd, new_fd;

// !! don't forget your error checking for these calls !!

// first, load up address structs with getaddrinfo():

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;  // use IPv4 or IPv6, whichever
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;     // fill in my IP for me

getaddrinfo(NULL, MYPORT, &hints, &res);

// make a socket, bind it, and listen on it:

sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
bind(sockfd, res->ai_addr, res->ai_addrlen);
listen(sockfd, BACKLOG);

// now accept an incoming connection:

addr_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size);

// ready to communicate on socket descriptor new_fd!
.
.
.
< /code>

struct sockaddr_storage their_addr
wird an (struct sockaddr *) & itaddr gegossen. Das Layout jeder Struktur ist: < /p>

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

and:

struct sockaddr_storage {
sa_family_t ss_family; // address family

// all this is padding, implementation specific, ignore it:
char __ss_pad1[_SS_PAD1SIZE];
int64_t __ss_align;
char __ss_pad2[_SS_PAD2SIZE];
};
< /code>

socktaddr_storage is definitely a bigger information storage, so it can be cast to whatever smaller than it to fit a function declaration. Inside the function, it does not matter what type of struct is, as long as the passed struct into the function has enough memory blocks for the function to operate as the required struct. Is this correct?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post