Hello! This question is related to another question I just posted. I'm prepping for a simple work project and am trying to familiarize myself with the basics of socket programming in a Unix dev environment. At this point, I have some basic server side code and client side code setup to communicate. Currently, my client code successfully connects to the server code and the server code sends it a test message, then both quit out. Perfect! That's exactly what I wanted to accomplish. Now I'm playing around with the functions used to obtain info about the two environments (server and client). I'd like to obtain my server program's IP address. Here's the code I currently have to do this, but it's not working...
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);
and the output for the IP is always empty...
server has TCP Port 21412 and IP Address ::
any ideas for what I'm missing?
thanks in advance for your help! this stuff is really complicated at first.