文章作者:里海
来源网站:https://blog.csdn.net/WangPaiFeiXingYuan
简介:
使用socket判断ip是否能联通
效果:
代码:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <winsock2.h>
#include <string>
#include <chrono>#pragma comment(lib, "ws2_32.lib")using namespace std;bool canConnectToRouter(string ipAddress)
{WSADATA wsaData;if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) // 初始化Windows Socket库 return false;int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // 创建一个TCP socket if (sockfd < 0) return false;struct sockaddr_in serveraddr;serveraddr.sin_addr.s_addr = inet_addr(ipAddress.c_str());serveraddr.sin_family = AF_INET;serveraddr.sin_port = htons(139);int ret = connect(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); // 连接服务器 if (ret < 0) {closesocket(sockfd);return false;}closesocket(sockfd);return true;
}int main()
{for (int i = 0; i < 256; i++){string ip = "192.168.16." + to_string(i);std::cout << ip << "\t";auto start = chrono::steady_clock::now(); // 记录开始时间 if (canConnectToRouter(ip.c_str()))std::cout << "InCompany\t";elsestd::cout << "NotInCompany\t";auto end = chrono::steady_clock::now(); // 记录结束时间 auto duration = chrono::duration_cast<chrono::milliseconds>(end - start); // 计算执行时间,单位为毫秒 cout << "耗时:" << duration.count() << "毫秒" << endl;}cin.get();
}