How To Copy The 4 Bytes To Sockaddr.sa_data?

- 1 answer

According to, I can use

std::string ip ="";
std::stringstream s(ip);
int a,b,c,d; //to store the 4 ints
char ch; //to temporarily store the '.'
s >> a >> ch >> b >> ch >> c >> ch >> d;
std::cout << a << "  " << b << "  " << c << "  "<< d;

to convert an IP to its 4 bytes. Buw how do I put them inside a

struct sockaddr
    __SOCKADDR_COMMON (sa_);    /* Common data: address family and length.  */
    char sa_data[14];       /* Address data.  */


Should I just simply copy the 4 bytes in the first 4 bytes of sa_data?



You don't actually use a struct sockaddr directly. You would instead populate a struct sockaddr_in which is made to hold an IPv4 address and port, then pass the address of that struct to functions that expect a struct sockaddr *.

To populate the address field of a sockaddr_in from a C string, you can use inet_addr.

For example:

struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(ip.c_str());
sin.sin_port = 0;

When calling recvfrom, the addrlen parameter should be a pointer to a variable which is set to the size of the structure pointed to by the src_addr parameter. For example:

struct sockaddr_in peerAddr;
socklen_t len = sizeof(peerAddr);
recvfrom(sock, data, capacity, 0, (struct sockaddr *)&peerAddr, &len);