Hi everyone,

I seem to be having a bit of a weird problem with sockaddr / sockaddr_in structs... I want to manually assign the value of an IP address to the sockaddr_in struct, and I've been using memcpy

memcpy (&(mIp4sa->sin_addr.s_addr), "", INET_ADDRSTRLEN);

But when I go to print out the IP address from the sockaddr_in struct using cout and inet_ntoa, I don't get the same address - in this case, I always seem to get or something similiar :S

I've tried casting a char* with the ip address to void* and using it in memcpy and the same thing happens... is this just something thats not possible or am I doing it wrong?

Thanks in advance for any help :)

Recommended Answers

All 4 Replies

Actually, I ended up getting it working now I think.. tried

inet_aton ("", &mIp4sa->sin_addr);

and its now working! :)

This post is effectively solved and needs to be marked as such, but for the reference of anyone coming along later, here's what happened:
The sin_addr contains a 32-bit unsigned long int. Not a string. as a number would look like 0x7F000001 or 2130706433 in decimal. The numbers 49, 50, 55, 46 are the ASCII codes for '1', '2', '7', and '.' respectively. A memcpy would do a byte for byte copy of the string "". I feel sorry for whoever's at They must get this all the time.

Instead you need to use inet_pton (inet_aton is now deprecated).
For a more in-depth look at sockets, have a look at the venerated Beej's Guide to Network Programming.

When Chuck Norris wants to roundhouse kick a browser into existence, he asks Beej for advice first.

Ah yes just realised after posting that inet_pton would be better since it would work with IP4 and IP6!

how it will be for IPv6 addresses.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.