C++网络编程--简单的WinSock代码
//注意要引用WinSock2的lib文件,否则编译不会通过
#include <WINSOCK2.H>
#include <stdio.h>
int main(int argc,char** argv)
{
WSADATA wsaData;
char HostName[256];
hostent* HostEnt;
protoent* ProtoEnt;
in_addr** Addr;
char* IPAddr;
SOCKET Socket;
sockaddr_in Sin;
SOCKET AcceptSocket;
//初始化WinSock
if(WSAStartup(MAKEWORD(2,2),&wsaData))
{
printf("Init WinSock failed!\n");
return 1;
}
//获取主机名
gethostname(HostName,256);
printf("%s\n",HostName);
//获取主机信息
HostEnt=gethostbyname(HostName);
printf("%s\n",HostEnt->h_name);
//枚举主机IP地址列表
Addr=(in_addr**)HostEnt->h_addr_list;
while(*Addr)
{
IPAddr=inet_ntoa(**Addr);
printf("%s\n",IPAddr);
Addr++;
}
//建立Socket
ProtoEnt=getprotobyname("TCP");
Socket=socket(AF_INET,SOCK_STREAM,ProtoEnt->p_proto);
if(Socket<0)
{
printf("Socket error!");
return 2;
}
//绑定Socket
Sin.sin_port=htons(23);
Sin.sin_family=AF_INET;
Sin.sin_addr.s_addr=0;
if(bind(Socket,(sockaddr*)&Sin,sizeof(Sin)))
{
printf("%s\n","Socket error!");
return 3;
}
//侦听请求
if(listen(Socket,1))
{
printf("%s","Socket error!");
return 4;
}
//
while (1)
{
AcceptSocket=SOCKET_ERROR;
while(AcceptSocket==SOCKET_ERROR)
{
AcceptSocket=accept(Socket,(sockaddr*)&Sin,NULL);
}
printf( "Client Connected.\n");
break;
}
char msg[]="\r\n==Connected!==\r\n";
printf("%d\n",send(AcceptSocket,msg,strlen(msg),0));
//关闭Socket收发功能
shutdown(AcceptSocket,0);
closesocket(AcceptSocket);
closesocket(Socket);
//取消被阻塞的Socket
if(WSAIsBlocking()) WSACancelBlockingCall();
//释放WinSock资源
WSACleanup();
return 0;
}