Convert IP address in sockaddr to uint32_t

12,300

Solution 1

It will work, yes.

According to the documentation, struct in_addr is defined as follows:

struct in_addr {
    uint32_t s_addr; /* address in network byte order */
};

so yes, you can assign it to a uint32_t (and you don't even need to cast it).

The "in network byte order" bit indeed also tells us that if you're running this on a machine that isn't big endian, you'll end up with garbage. You want to pass it through ntohl() to fix that.

Solution 2

This conversion will work okay, as long as you will not try to print clientIpAddr, and just re-use it in calls to sendto or bind.

To convert the address properly, you need to use ntohl function, which will convert from network to host byte order, otherwise your 0.0.0.1 address will have value 0x1000000 in clientIpAddr:

uint32_t clientIpAddr = ntohl(addr->sin_addr.s_addr);
Share:
12,300
Eddie
Author by

Eddie

Nowadays, I am interested in Vue.js, TypeScript, TDD, Unit Testing, Angular,React, Spring Cloud, MicroService, Java, Kubernetes,

Updated on June 22, 2022

Comments

  • Eddie
    Eddie almost 2 years

    I am tyring to convert IP address (v4) stored in struct sockaddr to uint32_t.

    //struct sockaddr in_addr;
    struct sockaddr_in* addr = (struct sockaddr_in*)&in_addr;
    
    uint32_t clientIpAddr = static_cast<uint32_t>(addr->sin_addr.s_addr);
    uint16_t clientPortNumber = addr->sin_port;
    

    First, I am wondering if this would work at all.

    Second, is it better to convert the IP address to char[4] and convert that to uint32_t later?

    Third, will IP address 0.0.0.1 be converted to number 1? or something else because of byte-order?