-1

I have a question concerning the use of union library winsock.h to convert the numbers to ipv4 address how to write?

#ifdef obsolete
        union {
                struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
                struct { u_short s_w1,s_w2; } S_un_w;
                u_long S_addr;
        } S_un;
lukassz
  • 3,135
  • 7
  • 32
  • 72

2 Answers2

1

This is one way to do it:

S_un addr;

addr.S_addr = htonl( 2655715960 );

printf("%hhu.%hhu.%hhu.%hhu  %hhX:%hhX:%hhX:%hhX \n",
       addr.S_un_b.s_b1, addr.S_un_b.s_b2, addr.S_un_b.s_b3, addr.S_un_b.s_b4,
       addr.S_un_b.s_b1, addr.S_un_b.s_b2, addr.S_un_b.s_b3, addr.S_un_b.s_b4 );

The magic number 2655715960 is the example input value from your comment. The code will print the wanted line:

158.75.2.120  9E:4B:2:78

Note: It is not common to print IPv4 addresses by using hex.

Note2: Use struct in_addr instead of S_un. So you can use inet_ntoa function for converting IP number to string.

SKi
  • 8,007
  • 2
  • 26
  • 57
0

Using my magic glass sphere, I'm trying to guess what's asked here:

sockaddr_storage could take IPv4 as well as IPv6 addresses.

ss_family indicates what's stored inside.

Depending on it's setting, it's either a sockaddr_in (for IPv4) or sockaddr_in6 (for IPv6) (http://msdn.microsoft.com/en-us/library/windows/desktop/ms740496(v=vs.85).aspx).

eckes
  • 64,417
  • 29
  • 168
  • 201