getaddrinfo( ) - getnameinfo( )/ inet_ntop( )

本文介绍了一个C语言程序,该程序使用getaddrinfo()函数解析主机名和服务端口,并通过addrinfo_ntop()函数将得到的地址信息转换为更易读的形式。程序还展示了如何使用getnameinfo()获取主机的反向DNS记录。



/*   addrinfo_ntop.c by vinco at 2012-05-18
 *   i386-Red Hat-gcc-4.1.2 
 *   http://blog.youkuaiyun.com/xuyunzhang/
 *   Copyright: All Reserved
 */

#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int addrinfo(char* host, char *serv);
int addrinfo_ntop(const struct addrinfo *paddrinfo,
                       char *host, size_t hostlen,
                       char *serv, size_t servlen);
int main()
{
	char host[64]="member.qq.com", serv[64]="8000";
	//char host[64]="183.60.49.253", serv[64]="8000";
	addrinfo( host, serv);
}

int addrinfo(char* host, char *serv)
{
	struct addrinfo hints, *res = NULL, *paddrinfo = NULL;
	char hostname[64]={0}, servname[64]={0};
	int ret = -1;

	if( !host || !serv )
		return -1;
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC; /* AF_INET6 or AF_INET */
	hints.ai_socktype = SOCK_DGRAM;
	//hints.ai_flags = ;
	
	if( (ret = getaddrinfo( host, serv, &hints, &res)) )
	{
		printf("getaddrinfo error:%s\n", gai_strerror(ret) );
		return -1;
	}
		
	for(paddrinfo = res; paddrinfo; paddrinfo = paddrinfo->ai_next )
	{
		if( addrinfo_ntop(paddrinfo,
					hostname, sizeof(hostname),
					servname, sizeof(servname)) == 0 )
		{
			ret = 0;
			fprintf(stderr, "addrinfo_ntop host/port = %s/%s\t", hostname, servname);
		}
		
		if( getnameinfo(paddrinfo->ai_addr, paddrinfo->ai_addrlen, 
					hostname, sizeof(hostname), 
					servname, sizeof(servname), 
					/*NI_NUMERICHOST | NI_NUMERICSERV*/ 0) == 0 ) 
		{
			ret = 0;
			fprintf(stderr, "getnameinfo host/port = %s/%s\n", hostname, servname);
		}
	}

	putchar('\n');
	
	freeaddrinfo(res);
	return ret;
	
}

int addrinfo_ntop(const struct addrinfo *paddrinfo,
                       char *host, size_t hostlen,
                       char *serv, size_t servlen)
{
	struct sockaddr_in *sain = NULL;
	struct sockaddr_in6 *sain6 = NULL;

	if( !paddrinfo || !host || !serv )
		return -1;
	switch ( paddrinfo->ai_family) 
	{
		case AF_INET: 
		{
			sain = (struct sockaddr_in *)(paddrinfo->ai_addr);
			inet_ntop( paddrinfo->ai_family, &(sain->sin_addr), host, hostlen);
			snprintf( serv, servlen, "%d", ntohs(sain->sin_port) );
			return 0;
		}
		break;

		case AF_INET6: 
		{
			sain6 = (struct sockaddr_in6 *)(paddrinfo->ai_addr);
			inet_ntop( paddrinfo->ai_family, &(sain6->sin6_addr), host, hostlen);
			snprintf( serv, servlen, "%d", ntohs(sain6->sin6_port) );
			return 0;
		};
		break;

		default:
		{
			return -1;
			break;
		}
	}
}

run && stdout


[root@localhost ctest]# 
[root@localhost ctest]# gcc addrinfo_ntop.c -o addrinfo_ntop
[root@localhost ctest]# 
[root@localhost ctest]# 
[root@localhost ctest]# ./addrinfo_ntop
addrinfo_ntop host/port = 58.251.150.157/8000	getnameinfo host/port = reverse.gdsz.cncnet.net/irdmi
addrinfo_ntop host/port = 112.90.143.245/8000	getnameinfo host/port = 112.90.143.245/irdmi

[root@localhost ctest]# 



[root@dcvserver03 Sunshine]# mkdir build mkdir: cannot create directory ‘build’: File exists [root@dcvserver03 Sunshine]# cd build [root@dcvserver03 build]# cmake .. \ > -DCMAKE_BUILD_TYPE=Release \ > -DBOOST_ROOT=/usr/local \ > -DBOOST_LIBRARYDIR=/usr/local/lib \ > -DMINIUPNP_INCLUDE_DIR=/usr/local/include \ > -DMINIUPNP_LIBRARY=/usr/local/lib/libminiupnpc.a /root/py/Sunshine Sunshine Branch: master PROJECT_NAME: Sunshine PROJECT_VERSION: 0.0.0 PROJECT_VERSION_MAJOR: 0 PROJECT_VERSION_MINOR: 0 PROJECT_VERSION_PATCH: 0 CMAKE_PROJECT_VERSION: 0.0.0 CMAKE_PROJECT_VERSION_MAJOR: 0 CMAKE_PROJECT_VERSION_MINOR: 0 CMAKE_PROJECT_VERSION_PATCH: 0 PROJECT_YEAR: 1990 PROJECT_MONTH: 01 PROJECT_DAY: 01 CMake Warning (dev) at cmake/macros/common.cmake:27 (_find_package): Policy CMP0144 is not set: find_package uses upper-case <PACKAGENAME>_ROOT variables. Run "cmake --help-policy CMP0144" for policy details. Use the cmake_policy command to set the policy and suppress this warning. CMake variable BOOST_ROOT is set to: /usr/local For compatibility, find_package is ignoring the variable, but code in a .cmake module might still use it. Call Stack (most recent call first): cmake/dependencies/Boost_Sunshine.cmake:33 (find_package) cmake/dependencies/common.cmake:5 (include) CMakeLists.txt:61 (include) This warning is for project developers. Use -Wno-dev to suppress it. -- Could NOT find Boost (missing: Boost_DIR) -- Boost v1.89.0 package not found in the system. Falling back to FetchContent. -- Boost: Release build, static libraries, MPI OFF, Python OFF, testing OFF -- Boost: libraries included: filesystem;locale;log;program_options;system;asio;crc;format;process;property_tree -- Boost.Charconv: quadmath support ON -- Boost.Context: architecture x86_64, binary format elf, ABI sysv, assembler gas, suffix .S, implementation fcontext -- Found the following ICU libraries: -- data (required): /usr/lib64/libicudata.so -- i18n (required): /usr/lib64/libicui18n.so -- uc (required): /usr/lib64/libicuuc.so -- Found ICU: /usr/include (found suitable version "50.2", minimum required is "4.8.1") -- Boost.Locale: iconv ON, ICU ON, POSIX ON, std ON, winapi OFF -- Found the following ICU libraries: -- data (required): /usr/lib64/libicudata.so -- i18n (required): /usr/lib64/libicui18n.so -- uc (required): /usr/lib64/libicuuc.so -- Found ICU: /usr/include (found version "50.2") -- Boost.Thread: threading API is pthread -- Boost include dirs: $<BUILD_INTERFACE:/root/py/Sunshine/build/_deps/boost-src/libs/headers/include> -- Boost libraries: Boost::filesystem;Boost::locale;Boost::log;Boost::program_options;Boost::system;Boost::asio;Boost::crc;Boost::format;Boost::process;Boost::property_tree -- Looking for fcntl -- Looking for fcntl - found -- Looking for ioctl -- Looking for ioctl - found -- Looking for poll -- Looking for poll - found -- Looking for getaddrinfo -- Looking for getaddrinfo - found -- Looking for getnameinfo -- Looking for getnameinfo - found -- Looking for gethostbyname_r -- Looking for gethostbyname_r - found -- Looking for gethostbyaddr_r -- Looking for gethostbyaddr_r - found -- Looking for inet_pton -- Looking for inet_pton - found -- Looking for inet_ntop -- Looking for inet_ntop - found -- Performing Test HAS_MSGHDR_FLAGS -- Performing Test HAS_MSGHDR_FLAGS - Success -- Check size of socklen_t -- Check size of socklen_t - done -- Check size of QOS_FLOWID -- Check size of QOS_FLOWID - failed -- Check size of PQOS_FLOWID -- Check size of PQOS_FLOWID - failed -- nlohmann_json v3.11.x package not found in the system. Falling back to FetchContent. -- Using the multi-header code from /root/py/Sunshine/build/_deps/json-src/include/ CMake Warning at third-party/libdisplaydevice/src/CMakeLists.txt:14 (message): Linux is not supported yet. -- nlohmann_json v3.11.x package not found in the system. Falling back to FetchContent. -- Checking for module 'miniupnpc' -- No package 'miniupnpc' found CMake Error at /usr/local/share/cmake-3.28/Modules/FindPkgConfig.cmake:619 (message): The following required packages were not found: - miniupnpc Call Stack (most recent call first): /usr/local/share/cmake-3.28/Modules/FindPkgConfig.cmake:841 (_pkg_check_modules_internal) cmake/dependencies/common.cmake:26 (pkg_check_modules) CMakeLists.txt:61 (include) -- Configuring incomplete, errors occurred! [root@dcvserver03 build]# [root@dcvserver03 build]# make -j$(nproc) VERBOSE=1 # 显示详细编译日志 make: *** No targets specified and no makefile found. Stop. [root@dcvserver03 build]# sudo make install make: *** No rule to make target `install'. Stop. [root@dcvserver03 build]# [root@dcvserver03 build]#
最新发布
11-19
libraries/avts/p2p/stun.o: In function `stunParseHostName': /home/wyl/Documents/NVMP/nvmp/build_dir/target-mips-openwrt-linux-uclibc-c510wv1/avts/streams/p2p/stun.c:1198: warning: gethostbyname is obsolescent, use getnameinfo() instead. libraries/nsd/httpd/httpd.o: In function `uhttpd_create_ecc_crt_key': /home/wyl/Documents/NVMP/nvmp/build_dir/target-mips-openwrt-linux-uclibc-c510wv1/nsd/modules/httpd/httpd.c:837: undefined reference to `tpssl_MakeEccCaCertPem' libraries/nsd/httpd/httpd.o: In function `https_handle': /home/wyl/Documents/NVMP/nvmp/build_dir/target-mips-openwrt-linux-uclibc-c510wv1/nsd/modules/httpd/httpd.c:554: undefined reference to `tpssl_MakeEccCaCertPem' collect2: error: ld returned 1 exit status Makefile:74: recipe for target 'link_main' failed make[4]: *** [link_main] Error 1 make[4]: Leaving directory '/home/wyl/Documents/NVMP/nvmp/build_dir/target-mips-openwrt-linux-uclibc-c510wv1/main' Makefile:159: recipe for target '/home/wyl/Documents/NVMP/nvmp/build_dir/target-mips-openwrt-linux-uclibc-c510wv1/main/.built' failed make[3]: *** [/home/wyl/Documents/NVMP/nvmp/build_dir/target-mips-openwrt-linux-uclibc-c510wv1/main/.built] Error 2 make[3]: Leaving directory '/home/wyl/Documents/NVMP/nvmp/tp_package/main' package/Makefile:105: recipe for target 'package/tp_package/main/compile' failed make[2]: *** [package/tp_package/main/compile] Error 2 make[2]: Leaving directory '/home/wyl/Documents/NVMP/nvmp' package/Makefile:101: recipe for target '/home/wyl/Documents/NVMP/nvmp/staging_dir/target-mips-openwrt-linux-uclibc-c510wv1/stamp/.package_compile' failed make[1]: *** [/home/wyl/Documents/NVMP/nvmp/staging_dir/target-mips-openwrt-linux-uclibc-c510wv1/stamp/.package_compile] Error 2 make[1]: Leaving directory '/home/wyl/Documents/NVMP/nvmp' /home/wyl/Documents/NVMP/nvmp/include/toplevel.mk:277: recipe for target 'world' failed make: *** [world] Error 2
09-20
CMakeFiles/cli_server.dir/port/wmnetLinux.c.o: In function `wmnetAddressResolve': wmnetLinux.c:(.text+0x398): warning: gethostbyname is obsolescent, use getnameinfo() instead. CMakeFiles/cli_server.dir/wmc_cli.c.o: In function `wmcli_smartLinkFailBackTime': wmc_cli.c:(.text+0xcbb8c): undefined reference to `cli_smartLinkFailBackTime' CMakeFiles/cli_server.dir/wmc_cli.c.o: In function `wmcli_smartlinkFailBack': wmc_cli.c:(.text+0xcbc28): undefined reference to `cli_smartLinkFailBack' CMakeFiles/cli_server.dir/wmc_cli.c.o: In function `wmcli_nosmartLinkFailBack': wmc_cli.c:(.text+0xcbcc0): undefined reference to `cli_smartLinkFailBack' CMakeFiles/cli_server.dir/wmc_cli.c.o: In function `wmcli_smartLinkGroupCreat': wmc_cli.c:(.text+0xcbd54): undefined reference to `cli_smartLinkGroupCreat' CMakeFiles/cli_server.dir/wmc_cli.c.o: In function `wmcli_nosmartLinkGroup': wmc_cli.c:(.text+0xcbde8): undefined reference to `cli_smartLinkGroupClean' CMakeFiles/cli_server.dir/wmc_cli.c.o: In function `wmcli_smartLinkEnable': wmc_cli.c:(.text+0xcbe24): undefined reference to `cli_smartLinkEnable' CMakeFiles/cli_server.dir/wmc_cli.c.o: In function `wmcli_nosmartLinkEnable': wmc_cli.c:(.text+0xcbe58): undefined reference to `cli_smartLinkEnable' CMakeFiles/cli_server.dir/wmc_cli.c.o:(.data.rel+0x8934): undefined reference to `wmcli_smartLinkFailBack' collect2: ld returned 1 exit status CMakeFiles/cli_server.dir/build.make:2588: recipe for target 'cli_server' failed make[3]: *** [cli_server] Error 1
10-22
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值