#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include<iostream>
#include<WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main() {
WSADATA wsaData;
WORD wsaVersion = MAKEWORD(2, 0);
WSAStartup(wsaVersion, &wsaData);
SOCKET serverSock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
addr.sin_addr.S_un.S_addr = INADDR_ANY;
bind(serverSock, (sockaddr*)&addr, sizeof(addr));
listen(serverSock, 100);
cout << "tcp server is listening at port 9999:" << endl;
SOCKET clientSock;
sockaddr_in clientaddr;
int len = sizeof(sockaddr_in);
while (true) {
clientSock = accept(serverSock, (sockaddr*)&clientaddr, &len);
if (INVALID_SOCKET != clientSock) {
cout << "client:" << inet_ntoa(clientaddr.sin_addr) <<
" "<<clientaddr.sin_port<<" is connected!" << endl;
closesocket(clientSock);
}
}
closesocket(serverSock);
WSACleanup();
return 0;
}
运行程序,然后win+r输入cmd,打开命令行窗口,输入 查看电脑ip地址 win+r输入cmd,打开命令行窗口,输入ipconfig 命令
|