TGViewer
C++ - Reddit C++ - Reddit @r_cpp · 229 subscribers
Post #24297 17
Do these posix socket functions completely overwrite the addr variable?

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
Reddit From the cpp community on Reddit Explore this post and more from the cpp community
More from @r_cpp
  1. Oct 12, 2026cppreference-doc for Qt Creator Release cppreference C++ v2025.12.01 · cristianadam/cppref…
  2. Oct 12, 2026ACCU Overload Journal 195 - October 2026 https://accu.org/journals/overload/overload195 ht…
  3. Oct 12, 2026C++ Contracts C++ contracts are a good thing, why are people saying it's a bad thing? Anyb…
  4. Oct 11, 2026wxWidgets 3.2.12 and 3.3.4 Released https://wxwidgets.org/news/2026/10/wxwidgets-3.2.12-an…
  5. Oct 11, 2026VKRT NES Remaster — an open-source C++20 NES emulator with an observation-driven remasteri…
  6. Oct 11, 2026Right way to test async code https://redd.it/1x2wqgz @r_cpp
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →