雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

C/C++语言中socket IP地址的结构体

2024-07-05 83

struct in_addr结构体

struct in_addr结构体是C/C++ socket编程中比较常用的结构体,主要是保存IP地址的信息,查看源码可以发现,这个结构体实际上是一个联合体,可以多种形式操作这个结构体。

struct in_addr {
    union {   
        struct {     
            u_char s_b1,s_b2,s_b3,s_b4;   
        } S_un_b;      //An IPv4 address formatted as four u_chars.  
        struct {     
            u_short s_w1,s_w2;   
        } S_un_w;   //An IPv4 address formatted as two u_shorts
        u_long S_addr; //An IPv4 address formatted as a u_long
    } S_un;
};

struct in_addr结构体使用

struct in_addr结构体的使用参考代码如下:

#includestdio.h
#includewinsock2.h

#pragma comment(lib, ws2_32.lib)

int main()
{
    in_addr addr;
    addr.S_un.S_un_b.s_b1 = 222;
    addr.S_un.S_un_b.s_b2 = 205;
    addr.S_un.S_un_b.s_b3 = 41;
    addr.S_un.S_un_b.s_b4 = 160;
    printf(%s\n, inet_ntoa(addr)); //222.205.41.160

    in_addr addr1;
    addr1.S_un.S_un_w.s_w1 = htons((222  8) + 205);
    addr1.S_un.S_un_w.s_w2 = htons((41  8) + 161);
    printf(%s\n, inet_ntoa(addr1)); //222.205.41.161

    in_addr addr2;
    addr2.S_un.S_addr = htonl((((((222  8) + 205)  8) + 41)  8) + 162);
    printf(%s\n, inet_ntoa(addr2)); //222.205.41.162
}
更新于:4个月前
赞一波!2

文章评论

评论问答