Does the following piece of code contains an Undefined Behavior? The code only tries to fill sockaddr_storage
structure with sockaddr_in
structure format and then read it back via same type ie. sockaddr_in
. Also in the following calls, that sockaddr_storage
structure is passed with a cast to sockaddr
structure. I saw similar question and wondering if this code contains it too. This program works fine wherever I've tested it -
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
void fillAF_INET(sockaddr_storage &s){
sockaddr_in *p = reinterpret_cast<sockaddr_in *>(&s);
p->sin_family = AF_INET;
p->sin_port = htons(10000);
inet_pton(AF_INET, "127.0.0.1", &p->sin_addr);
}
// void fillAF_INET6(sockaddr_storage &s){...}
// void fillAF_UNIX(sockaddr_storage &s){...}
int main(){
sockaddr_storage s;
fillAF_INET(s);
sockaddr_in *p = reinterpret_cast<sockaddr_in *>(&s);
std::cout << ntohs(p->sin_port) << " ";
std::cout << boolalpha << (p->sin_family == AF_INET);
int sock = socket(AF_INET, SOCK_STREAM,0);
int r = bind(sock, (sockaddr *)&s, sizeof(s));
// further calls
return 0;
}
The result comes : 10000 true
which is absolutely correct!