Need help getting TCP port number and IP address in C

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 11:13:51
kpaleniu

The problem is in your inet_ntop call:

inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
          host, sizeof host);

In here you are using pointer p after calling

freeaddrinfo(servinfo);

You need to copy the struct sockaddr and socklen_t you got from getaddrinfo in some variables, or store the struct addrinfo for further use. Otherwise you will cause undefined behavior, like you are now experiencing. Remember, Valgrind is your friend.

What you might need to use is the getsockname function:

struct sockaddr_storage my_addr;
socklen_t my_addr_len = sizeof(my_addr);
if (getsockname(sockfd, (struct sockaddr *) &my_addr, &my_addr_len) != -1)
{
#ifndef NI_MAXHOST
# define NI_MAXHOST 1025
#endif
#ifndef NI_MAXSERV
# define NI_MAXSERV 32
#endif

    char host[NI_MAXHOST];
    char serv[NI_MAXSERV];

    if (getnameinfo((const struct sockaddr *) &my_addr, my_addr.ss_len,
                    host, sizeof(host),
                    serv, sizeof(serv), 0) == 0)
    {
        printf("Host address: %s, host service: %s\n", host, serv);
    }
}

Well, the other answers (getsockname) is probably already what you need.

I just would like to highlight one of the best sources available to understanding network programming:

Beej's guide to network programming

  • it's reasonably short, you work through it within 1 hour
  • works for both, windows and linux (and unix etc...)
  • explains the concepts behind in the necessary detail (no fuss where not necessary)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!