In this code snippet I am trying to reuse the addr variable to read multiple socket addresses into it under the assumption that functions like getsockname, getpeername *completely* overwrite the `addr` bits. Is my assumption correct? I am trying to reuse my variables here instead of creating new ones.
int main(int argc, char **argv) {int fd = socket(AF_INET, SOCK_STREAM, 0);if (fd < 0) {die("socket()");}struct sockaddr_in addr = {};addr.sin_family = AF_INET;addr.sin_port = htons(1234);addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);int rv = connect(fd, (const struct sockaddr *)&addr, sizeof(addr));socklen_t len = sizeof(addr);unsigned short client_port = 0;if (!getsockname(fd, (struct sockaddr *)&addr, &len)) {client_port = ntohs(addr.sin_port);}if (rv) {die("connect");} else {socklen_t len = sizeof(addr);int remote = getpeername(fd, (struct sockaddr *)&addr, &len);if (remote) {printf("error getting remote address\n");} else {char ip[INET_ADDRSTRLEN];inet_ntop(AF_INET, &addr.sin_addr, ip, sizeof(ip));printf("connected to server @ <%s:%d>", ip, ntohs(addr.sin_port));}if (client_port != 0 && remote == 0)printf(" | client port <%d>\n", client_port);}const char *data = argc > 1 ? argv[1] : "hello!";write(fd, data, strlen(data));char rbuf[64] = {};ssize_t n = read(fd, rbuf, sizeof(rbuf) - 1);if (n < 0) {die("read");}printf("server says: %s\n", rbuf);close(fd);return 0;}https://redd.it/1p25aru
@r_cpp