linux c socket之GetAddrInfo

发布时间:2014-10-23 23:25:22
来源:分享查询网

/* * File: GetAddrInfo.c * Author: 云守护 */ #include <stdio.h> #include <stdlib.h> #include <limits.h> #include <stdint.h> #include <string.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include "DieWithMessage.h" void PrintSocketAddress(const struct sockaddr *address, FILE *stream) { // Test for address and stream if (address == NULL || stream == NULL) return; void *numericAddress; // Pointer to binary address // Buffer to contain result (IPv6 sufficient to hold IPv4) char addrBuffer[INET6_ADDRSTRLEN]; in_port_t port; // Port to print // Set pointer to address based on address family switch (address->sa_family) { case AF_INET: numericAddress = &((struct sockaddr_in *) address)->sin_addr; port = ntohs(((struct sockaddr_in *) address)->sin_port); break; case AF_INET6: numericAddress = &((struct sockaddr_in6 *) address)->sin6_addr; port = ntohs(((struct sockaddr_in6 *) address)->sin6_port); break; default: fputs("[unknown type]", stream); // Unhandled type return; } // Convert binary to printable address if (inet_ntop(address->sa_family, numericAddress, addrBuffer, sizeof (addrBuffer)) == NULL) fputs("[invalid address]", stream); // Unable to convert else { fprintf(stream, "%s", addrBuffer); if (port != 0) // Zero not valid in any socket addr fprintf(stream, "-%u", port); } } int main(int argc, char** argv) { if (argc != 3) { DieWithUserMessage("param", "<Address/Name> <Port/Service>"); } char* addrString = argv[1]; char* portString = argv[2]; //地址信息结构体,单链表结构 struct addrinfo addrCriteria; //结构体置零 memset(&addrCriteria, 0, sizeof (addrCriteria)); addrCriteria.ai_family = AF_UNSPEC; addrCriteria.ai_socktype = SOCK_STREAM; addrCriteria.ai_protocol = IPPROTO_TCP; //单链表结构 struct addrinfo *addrList; //获取地址信息 int retVal = getaddrinfo(addrString, portString, &addrCriteria, &addrList); if (retVal != 0) DieWithUserMessage("getaddrinfo() failed!", (const char*) gai_strerror(retVal)); struct addrinfo *addr = addrList; while (addr != NULL) { //处理地址信息 PrintSocketAddress(addr->ai_addr, stdout); fputc('\n', stdout); addr = addr->ai_next; } freeaddrinfo(addrList); return (EXIT_SUCCESS); }

返回顶部
查看电脑版