WinSock网络编程学习笔记(六):服务查询程序(getserverbyname和getserverbyport函数)

#include<stdlib.h>
#include<stdio.h>
#include<winsock2.h>

#pragma comment(lib,"ws2_32")

//概要:初步学习getservbyname和getservbyport函数的用法
/*
函数原型:
1. struct servent FAR *WSAAPI getservbyname(const char FAR *name,const char FAR *proto);
2. struct servent FAR *WSAAPI getservbyport(int port,const char FAR *proto);
返回值:
成功时返回指向 servent结构的指针;失败返回NULL,可以调用WSAGetLastError()得到具体的代码。
*/

void serv_print(struct servent *serv_info,const char *serv_name,short port)
{
	char **list_p;
	if(serv_info == NULL)
	{
		printf("_____________________________\n");
		if(serv_name)
			printf("can't get service: %s\n",serv_name);
		else 
			printf("cant't get service op port:%d\n",port);
	}
	else 
	{
		printf("______________________________\n");
		printf("offical name:%s\n",serv_info->s_name);
		if(*serv_info->s_aliases)
			printf("alias:\n");
		for(list_p = serv_info->s_aliases;*list_p != NULL;list_p++)
			printf("\t%s\n",*list_p);
		printf("port: %d\n",ntohs(serv_info->s_port));
		printf("protocol:%s\n",serv_info->s_proto);
	}

}
int main(int argc,char* argv[])
{
	const char *proto = "tcp";
	const char *serv_name[] = {"domain","http","invalid"};	//要查询的服务名数组
	int i,serv_cnt = sizeof(serv_name) / sizeof(serv_name[0]);
	short port_num[] = {7,88};								//要查询的端口号数组
	int port_cnt = sizeof(port_num) / sizeof(port_num[0]);
	struct servent *serv_info;
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,0),&wsaData);
	printf("[getservbyname] get service by name\n");
	for( i = 0;i<serv_cnt;i++)								//在每个服务名字上调用getservbyname来查询对应的服务信息
	{
		serv_info = getservbyname(serv_name[i],proto);
		serv_print(serv_info,serv_name[i],0);
	}
	printf("\n[getservbyport] get service by port\n");
	for(i = 0;i<port_cnt;i++)
	{
		serv_info = getservbyport(htons(port_num[i]),proto);
		serv_print(serv_info,NULL,port_num[i]);
	}
	WSACleanup();
	return 0;
}

你可能感兴趣的:(网络编程,NetWork)