【发布时间】:2010-03-22 23:19:24
【问题描述】:
此问题与another question I just posted 有关。我正在为一个简单的工作项目做准备,并试图让自己熟悉 Unix 开发环境中套接字编程的基础知识。在这一点上,我有一些基本的服务器端代码和客户端代码设置来进行通信。目前,我的客户端代码成功连接到服务器代码,服务器代码向它发送了一条测试消息,然后都退出了。完美的!这正是我想要完成的。现在我正在使用用于获取有关两个环境(服务器和客户端)信息的函数。我想获取我的服务器程序的 IP 地址。这是我目前必须执行此操作的代码,但它不起作用...
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 ::
对我缺少的东西有什么想法吗?
提前感谢您的帮助!这东西一开始真的很复杂。
【问题讨论】: