1、由文件描述符打印IP地址及端口。(参考)
#include <stdio.h> #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> //由文件描述符打印对应IP地址和端口 void PrintAddrByFd(int sockfd) { struct sockaddr_in addr_in; socklen_t len = sizeof(addr_in); getsockname(sockfd, (struct sockaddr *)&addr_in, &len); if (addr_in.sin_family != AF_INET) { printf("Not an Internet socket.\n"); return; } printf("addr:%s, port:%d\n", inet_ntoa(addr_in.sin_addr), ntohs(addr_in.sin_port)); }
2、打印本机所有IP地址。
#include <stdio.h> #include <ifaddrs.h> #include <netinet/in.h> //打印本机所有IP地址 int main (int argc, const char * argv[]) { struct ifaddrs * ifAddrStruct = NULL; void * tmpAddrPtr = NULL; getifaddrs(&ifAddrStruct); while (ifAddrStruct != NULL) { if (ifAddrStruct->ifa_addr->sa_family == AF_INET) { // check it is IP4 // is a valid IP4 Address tmpAddrPtr = &((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); printf("%s IPV4 Address %s\n", ifAddrStruct->ifa_name, addressBuffer); } else if (ifAddrStruct->ifa_addr->sa_family == AF_INET6) { // check it is IP6 // is a valid IP6 Address tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr; char addressBuffer[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); printf("%s IPV6 Address %s\n", ifAddrStruct->ifa_name, addressBuffer); } ifAddrStruct = ifAddrStruct->ifa_next; } return 0; }
参考链接:
*** walker ***
本文出自 “walker的流水账” 博客,请务必保留此出处http://walkerqt.blog.51cto.com/1310630/1741099
原文地址:http://walkerqt.blog.51cto.com/1310630/1741099