c - How to memcpy() a struct sockaddr_in -
i'm programming server-client program. on server manage clients through array of data structure:
struct client { struct sockaddr_in addr; /*...*/ }; struct client clients[max_cli];
when receive first packet client through udp
socket
struct sockaddr_in addr_cli; memset(&addr_cli,0,sizeof(struct sockaddr_in)); b=recvfrom(sock_udp_father, &pdu, sizeof(pdu), msg_dontwait, (struct sockaddr *)&addr_cli, (socklen_t *)&laddr_cli);
i want copy address struct. do:
memcpy(&clients[client].addr,(struct sockaddr*)&addr_cli, sizeof(struct sockaddr_in)); printf("ip client: %s",inet_ntoa(clients[client].addr.sin_addr);
the strange thing first try of communication fails, printing 0.0.0.0
. next try client does, successful , goes fine. why happens?
the addr_cli
not filled call recvfrom
. last 2 arguments of recvfrom
little bit tricky. are
struct sockaddr *src_addr, socklen_t *addrlen
if src_addr
not null, recvfrom
expects addrlen
points length of src_addr
buffer. (normally size of sockaddr
structure). if value of addrlen
small, returned address truncated. after call recvfrom
addrlen
set actual address length. @ documentation details.
so need initialize laddr_cli
before calling recvfrom()
:
struct sockaddr_in addr_cli; socklen_t laddr_cli = sizeof(addr_cli); // <-- memset(&addr_cli,0,laddr_cli); b=recvfrom(sock_udp_father, &pdu, sizeof(pdu), msg_dontwait, (struct sockaddr *)&addr_cli, &laddr_cli);
Comments
Post a Comment