How to get the IP address of my server program?

This question is related to another question I just posted . I am preparing for a simple working project and trying to get acquainted with the basics of socket programming in a Unix dev environment. At the moment, I have the base code on the server side and setting up the client side code for communication. Currently, my client code successfully connects to the server code, and the server code sends him a test message, after which both are completed. Fine! This is exactly what I wanted to achieve. Now I play with the functions used to get information about these two environments (server and client). I would like to get the IP address of my server program. Here is the code that I have to do now, but it does not work ...

int sockfd;
unsigned int len;
socklen_t sin_size;
char msg[]="test message";
char buf[MAXLEN];
int st, rv;
struct addrinfo hints, *serverinfo, *p; 
struct sockaddr_storage client;
char s[INET6_ADDRSTRLEN];
char ip[INET6_ADDRSTRLEN];

//zero struct   
memset(&hints,0,sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;

//get the server info
if((rv = getaddrinfo(NULL, SERVERPORT, &hints, &serverinfo ) != 0)){
  perror("getaddrinfo");
  exit(-1);
}

// loop through all the results and bind to the first we can
for( p = serverinfo; p != NULL; p = p->ai_next)
{
  //Setup the socket
  if( (sockfd = socket( p->ai_family, p->ai_socktype, p->ai_protocol )) == -1 )
  {
    perror("socket");
    continue;
  }

  //Associate a socket id with an address to which other processes can connect
  if(bind(sockfd, p->ai_addr, p->ai_addrlen) == -1){
    close(sockfd);
    perror("bind");
    continue;
  }

  break;
}

if( p == NULL ){
  perror("Fail to bind");
}

inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof(s));
printf("Server has TCP Port %s and IP Address %s\n", SERVERPORT, s);

IP ...

server has TCP Port 22513 and IP Address ::

- , ?

! .

+3
2

, /. "::" IPv6 "0: 0: 0: 0: 0: 0: 0: 0", , .

, , , getaddrinfo() addrinfo , , , IPv6 , , . , ...

+2

, , , , , , /. IP-, , , , TCP- .

, getaddrinfo(), :

  • AF_UNSPEC ai_family ,
  • SOCK_STREAM ai_socktype
  • AI_PASSIVE, ai_flags, ,
    • nodename NULL, IP- INADDR_ANY IPv4- IN6ADDR_ANY_INIT IPv6-

IPv6 IPv4 RFC 3484, getaddrinfo() IPv6- ( "0: 0: 0: 0: 0: 0: 0: 0" ).

inet_ntop() IPv6 "::".


, , gethostname() getaddrinfo(). AF_UNSPEC ai_family, nodename . IP- INADDR_ANY/IN6ADDR_ANY_INIT, TCP- .

0

Source: https://habr.com/ru/post/1738108/


All Articles