#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
WORD mvVersionRequest;
WSADATA wsaData; //声明一个套节字结构体
int err;
err=WSAStartup(MAKEWORD(2,2),&wsaData);
!err?printf("已打开套接字\n"):printf("套接字打开失败\n");
SOCKET servSock = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
//绑定套节字,用一个结构体并填写数扰
SOCKADDR_IN sockAddr;
memset(&sockAddr,0,sizeof(sockAddr)); //初始化为0
sockAddr.sin_family=AF_INET;
sockAddr.sin_addr.S_un.S_addr =inet_addr("127.0.0.1");
sockAddr.sin_port=htons(6000);
bind(servSock,(SOCKADDR*)&sockAddr,sizeof(SOCKADDR));
listen(servSock,20);
SOCKADDR_IN clintAddr;
int nSize = sizeof(SOCKADDR);
while(1)
{
//第二次握手
SOCKET clntSock = accept(servSock,(SOCKADDR*)&clintAddr,&nSize);//获得客户端套节定大小
//就可以向客户端发送信息,如果有服务就存在数据库,供调用
char sendBuffer[128];
sprintf(sendBuffer,"连接成功,您的IP是:%s",inet_ntoa(clintAddr.sin_addr));
send(clntSock,sendBuffer,strlen(sendBuffer)+1,NULL);
char receiveBuffer[128];
recv(clntSock,receiveBuffer,strlen(receiveBuffer)+1,NULL);
printf("%s\n",receiveBuffer);
//重点,一定要关闭
closesocket(clntSock);
WSACleanup();
}
closesocket(servSock);
WSACleanup();
return 0;
}