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), "127.0.0.1", 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 49.50.53.49 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 :)

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

inet_aton ("127.0.0.1", &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. 127.0.0.1 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 "127.0.0.1". I feel sorry for whoever's at 49.50.55.46. 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, networking, learning, and sharing knowledge.