2

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 -

Run Online

#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!

hg_git
  • 2,884
  • 6
  • 24
  • 43

1 Answers1

3

Code is correct. Here is what the Open Group says about sockaddr_storage:

The <sys/socket.h> header shall define the sockaddr_storage structure. This structure shall be:

  • Large enough to accommodate all supported protocol-specific address structures

  • Aligned at an appropriate boundary so that pointers to it can be cast as pointers to protocol-specific address structures and used to access the fields of those structures without alignment problems

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • 2
    'It is correct' - do you mean it is UB or the code is correct and it is not UB? See also https://stackoverflow.com/questions/42178179/will-casting-around-sockaddr-storage-and-sockaddr-in-break-strict-aliasing – harmic Feb 15 '17 at 07:19
  • 1
    This is wrong, see also - http://stackoverflow.com/questions/42176962/fill-sockaddr-storage-struct-with-values-of-sockaddr-in – Abhinav Gauniyal Feb 15 '17 at 07:57