Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IP address in sockaddr to uint32_t

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?

like image 457
Eddie Avatar asked Dec 19 '22 23:12

Eddie


2 Answers

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.

like image 93
Wouter Verhelst Avatar answered Jan 04 '23 15:01

Wouter Verhelst


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);
like image 34
pelya Avatar answered Jan 04 '23 16:01

pelya