#include <stdio.h> 
#include <WINSOCK2.H> 
#include <iostream.h> 
void main() 

printf("Service waiting\n"); 
WORD wVersionRequested; 
WSADATA WSAData; 
int err; 
wVersionRequested=MAKEWORD(1,1); 
err=WSAStartup(wVersionRequested,&WSAData); 
if (err!=0) 

cout < <"WSAStartup failed:" < <WSAGetLastError() < <endl; 
return; 

if (LOBYTE(WSAData.wVersion)!=1||HIBYTE(WSAData.wVersion)!=1) 

WSACleanup(); 
cout < <"WSAStartup failed:type not fill" < <endl; 
return; 

SOCKET sockServ=socket(AF_INET,SOCK_STREAM,0); 
SOCKADDR_IN addrSrv; 
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//INADDR_ANY本身就是一个值为0的宏,在此可以不强制转换 
addrSrv.sin_port=htons(5000); 
err=bind(sockServ,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)); 
if (err!=0) 

cout < <"bind failed:" < <WSAGetLastError() < <endl; 
return; 

listen(sockServ,5); 
SOCKADDR_IN addrClient; 
int len; 
len=sizeof(SOCKADDR); 
int n=1; 
while (1) 
{ SOCKET sockConn=accept(sockServ,(SOCKADDR*)&addrClient,&len); 
char sendBuf[100]; 
sprintf(sendBuf,"欢迎 %s:%d访问我的服务器",inet_ntoa(addrClient.sin_addr),ntohs(addrClient.sin_port)); 
send(sockConn,sendBuf,strlen(sendBuf)+1,0); 
char recvBuf[100]; 
recv(sockConn,recvBuf,100,0); 
printf("%s\n",recvBuf); 
closesocket(sockConn); 
n++; 
/*if (n==2) 

break; 
}*/ } }

解决方案 »

  1.   

    Error Codes 
    WSANOTINITIALISED     A successful WSAStartup must occur before using this function. 
    WSAENETDOWN           The network subsystem has failed. 
    WSAEADDRINUSE         A process on the machine is already bound to the same fully-qualified address
                          and the socket has not been ed to allow address re-use with SO_REUSEADDR.
                          For example, IP address and port are bound in the af_inet case) . (See the 
                          SO_REUSEADDR socket option under setsockopt.) 
    WSAEADDRNOTAVAIL      The specified address is not a valid address for this machine 
    WSAEFAULT             The name or the namelen parameter is not a valid part of the user address 
                          space, the namelen parameter is too small, the name parameter contains 
                          incorrect address format for the associated address family, or the first two 
                          bytes of the memory block specified by name does not match the address family 
                          associated with the socket descriptor s. 
    WSAEINPROGRESS        A blocking Windows Sockets 1.1 call is in progress, or the service provider 
                          is still processing a callback function. 
    WSAEINVAL             The socket is already bound to an address. 
    WSAENOBUFS            Not enough buffers available, too many connections. 
    WSAENOTSOCK           The descriptor is not a socket. 要知道错误类型是那个,你可以把那类型写入VC中,如把WSAENOTSOCK写入,把光标放在WSAENOTSOCK上,点击右键选择到WSAENOTSOCK的定义。这样就能看到WSAENOTSOCK代表的值是什么了。