#include<Winsock2.h>
#include<stdio.h>
#include<stdlib.h>
#define PORT 5000
void main()
{
int port=PORT;
WSADATA wsaData;
SOCKET sListen,sAccept;
int iLen; //客户地址长度
int iSend; //发送数据长度
char buf[]="Hello,How are you!"; //需要发送信息
struct sockaddr_in serv,cliet; //服务器、客户的地址
if(WSAStartup(MAKEWORD(2,2),&wsaData)!=0)
{
printf("Winsock load failed/n");
return;
}
//创建套接字
sListen=socket(AF_INET,SOCK_STREAM,0);
if(sListen==INVALID_SOCKET)
{
printf("socket failed:%d/n",WSAGetLastError());
return;
}
else
{
printf("socket OK!");
}
//建立服务器地址
serv.sin_family=AF_INET;
//把一个双字节主机字节顺序的数据转换为网络字节顺序
serv.sin_port=htons(port);
//把四个字节主机字节顺序转换为网络字节顺序,INADDR_ANY为系统指定的IP地址
serv.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(sListen,(LPSOCKADDR)&serv,sizeof(serv))==SOCKET_ERROR)
{
printf("bind() failed:%d/n",WSAGetLastError());
return;
}
else
{
printf("bind() OK/n");
}
//进入监听状态
if(listen(sListen,5)==SOCKET_ERROR)
{
printf("listen() failed:%d/n",WSAGetLastError());
return;
}
else
{
printf("listen() OK/n");
}
iLen=sizeof(cliet); //初始化客户地址长度
//进入循环,等待客户连接请求
while(1)
{
sAccept=accept(sListen,(struct sockaddr*)&cliet,&iLen);
if(sAccept==INVALID_SOCKET)
{
printf("accept() failed:%d/n",WSAGetLastError());
break;
}
//输出已连接客户IP地址和端口
printf("accepted client IP:[%s],port:[%d]/n",inet_ntoa(cliet.sin_addr),ntohs(cliet.sin_port));
iSend=send(sAccept,buf,sizeof(buf),0);
if(iSend==SOCKET_ERROR)
{
printf("send() failed:%d/n",WSAGetLastError());
break;
}
else if(iSend==0) break;
else
printf("send() byte:%d/n",send);
closesocket(sAccept);
}
closesocket(sListen);
WSACleanup();
}