正在做一个socket服务程序,在绑定时地址使用的是INADDR_ANY。现在服务器上有多个网卡,客户端会连接其中的任何一个网卡,现在想在服务端accpet时知道客户端是通过服务器的哪个网卡(或者IP)连接进来的?使用了getsockname函数,但是获取出来的ip是 0.0.0.0,不知道还有其它方法可以获取到这个信息吗?
socket
------解决方案--------------------------------------------------------
用getsockname是木有问题的,关键是要对accept返回值使用getsockname, 不是进行listen的那个描述字
/**
* @file sockname.c
* @brief
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
struct sockaddr_in lisnaddr, clntaddr, addr;
socklen_t clntlen, len;
int lisnfd, clntfd;
char *ptr;
int optval;
memset(&lisnaddr, 0, sizeof(lisnaddr));
lisnaddr.sin_family = AF_INET;
lisnaddr.sin_addr.s_addr = htonl(INADDR_ANY);
lisnaddr.sin_port = htons(8888);
lisnfd = socket(AF_INET, SOCK_STREAM, 0);
optval = 1;
setsockopt(lisnfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
bind(lisnfd, (struct sockaddr *)&lisnaddr, sizeof(lisnaddr));
listen(lisnfd, 5);
clntlen = sizeof(clntaddr);
clntfd = accept(lisnfd, (struct sockaddr *)&clntaddr, &clntlen);
len = sizeof(addr);
getsockname(clntfd, (struct sockaddr *)&addr, &len);
ptr = inet_ntoa(addr.sin_addr);
printf("%s:%d <==> ", ptr, htons(addr.sin_port));
ptr = inet_ntoa(clntaddr.sin_addr);
printf("%s:%d\n", ptr, htons(clntaddr.sin_port));
return 0;
}
fb82:/home/mymtom/src/csdn$ make sockname
cc -O2 -pipe sockname.c -o sockname
fb82:/home/mymtom/src/csdn$ ./sockname
192.168.118.130:8888 <==> 192.168.118.1:52649