查詢本機上TCP協議的所有服務
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include "WinSock2.h"
#include "iostream"
#pragma comment(lib,"ws2_32.lib") //鏈接WinSock導入庫
using namespace std;
int main(int argc, char **argv) {
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD(2, 2); //調用2.2版本
if (WSAStartup(wVersionRequested, &wsaData) != 0) { //加載WinSock動態鏈接庫
cout << "加載WinSock DLL失敗!\n";
return 0;
}
struct servent *pServer;
for (int i = 1; i < 65535; i++) {
pServer = getservbyport(htons(i), "TCP");//獲取服務信息
if (pServer != NULL) {
cout << "服務名:" << pServer->s_name << endl;
cout << "協議:" << pServer->s_proto << endl;
cout << "端口號:" << ntohs(pServer->s_port) << endl;
}
}
WSACleanup();
return 0;
}