方法1,按com口编号循环打开关闭,能打开的就列出。
#include <stdio.h>
#include <string.h>
#include <winsock.h>
int main(int argc, char *argv[]) {
int mysocket;
int pcount = 0;
struct sockaddr_in my_addr;
WSADATA wsaData;
WORD wVersionRequested=MAKEWORD(1,1);
if(argc < 3) {
printf("usage: %s <host> <maxport>\n", argv[0]);
exit(1);
}
if (WSAStartup(wVersionRequested , &wsaData)){
printf("Winsock Initialization failed.\n");
exit(1);
}
for(int i=1; i < atoi(argv[2]); i++){
if((mysocket = socket(AF_INET, SOCK_STREAM,0)) == INVALID_SOCKET){
printf("Socket Error");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(i);
my_addr.sin_addr.s_addr = inet_addr(argv[1]);
if(connect(mysocket, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == SOCKET_ERROR)
closesocket(mysocket);
else{
pcount++;
printf("Port %d - open\n", i);
}}
printf("%d ports open on host - %s\n", pcount, argv[1]);
closesocket(mysocket);
WSACleanup();
return 0;
}