使用套接字编程API(例如,socket(),connect(),accept()…),如何知道同一台机器上的两个进程之间是否有TCP连接?说,我有socket文件描述符和远程ip.我可以简单地检查远程ip是127.0.0.1吗?
解决方法
这是我使用的方法.这个想法是尝试将侦听器绑定到该IP地址,并使用故障/成功代码来确定地址是否为本地地址.
我不是说这是特别有效的,但它应该是相当可靠的,对我的申请是适当的.
#include <sys/socket.h> #include <errno.h> /* ...probably need some other headers I am forgetting... */ int is_local(const struct sockaddr *addr,socklen_t addr_len) { const char *func = "is_local()"; int result = 0; int tmp = socket(addr->sa_family,SOCK_STREAM,0); if (tmp < 0) { printf("%s: socket(%d,0) Failed,errno %d\n",func,addr->sa_family); goto out; } /* If bind() succeeds,or if it fails because the address is in use,then the address must be local to this system. */ if (bind(tmp,addr,addr_len) < 0) { if (errno == EADDRINUSE) result = 1; else if (errno == EADDRNOTAVAIL) ; /* do nothing; address is remote */ else printf("%s: bind() unexpected error %d\n",errno); } else { result = 1; } close(tmp); out: return result; }
你这样称呼:
struct sockaddr_storage client_addr; socklen_t client_addr_len = sizeof(client_addr); int fd = accept(listener,&client_addr,&client_addr_len); if (is_local((struct sockaddr *)&client_addr,client_addr_len)) /* peer is local */