WinSock 네트워크 프로그래밍 학습 노트 (6): 서비스 검색 프로그램 (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("_____________________________
"); if(serv_name) printf("can't get service: %s
",serv_name); else printf("cant't get service op port:%d
",port); } else { printf("______________________________
"); printf("offical name:%s
",serv_info->s_name); if(*serv_info->s_aliases) printf("alias:
"); for(list_p = serv_info->s_aliases;*list_p != NULL;list_p++) printf("\t%s
",*list_p); printf("port: %d
",ntohs(serv_info->s_port)); printf("protocol:%s
",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
"); for( i = 0;i<serv_cnt;i++) // getservbyname { serv_info = getservbyname(serv_name[i],proto); serv_print(serv_info,serv_name[i],0); } printf("
[getservbyport] get service by port
"); 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; }

좋은 웹페이지 즐겨찾기