从sockaddr_in 中提取IP 和端口

 sockaddr_in 结构体如下:

struct in_addr {
  union {
    struct {
      u_char s_b1;
      u_char s_b2;
      u_char s_b3;
      u_char s_b4;
    } S_un_b;
    struct {
      u_short s_w1;
      u_short s_w2;
    } S_un_w;
    u_long S_addr;
  } S_un;
};

struct sockaddr {
        ushort  sa_family;
        char    sa_data[14];
};

struct sockaddr_in {
        short   sin_family;
        u_short sin_port;
        struct  in_addr sin_addr;
        char    sin_zero[8];
};

实际代码:

    sockaddr_in sin;  
    sin.sin_family = AF_INET;  
    sin.sin_port = htons(12345);  
    //sin.sin_addr.S_un.S_addr = INADDR_ANY;   
    sin.sin_addr.S_un.S_addr =inet_addr("222.111.44.222");

从sockaddr_in 中提取IP 和端口_第1张图片

内存中

 02 00 30 39 de 6f 2c de cc cc cc cc cc cc cc cc

从sockaddr_in 中提取IP 和端口_第2张图片

0xde=222  0x6f=111 0x2c=44 

还原出来IP端口 222.111.44.222:12345

 

你可能感兴趣的:(杂)