服务器代码:
#include<winsock2.h>
#include<iostream>
#include<windows.h>
using namespace std;
//extern "C"{
int main(int argc, char** argv){
int clientlen;
struct sockaddr_in clientaddr;
struct hostent *hp;
char *haddrp;
char chInfo[64];
WSADATA wsaData;
int ret = WSAStartup(MAKEWORD(2,2), &wsaData);
if(ret != 0){
cout << "Error" << endl;
WSACleanup();
}
if (gethostname(chInfo, sizeof(chInfo)))
cout<<"\n无法获取主机!\n ";
cout << chInfo << endl;
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(serverSocket==INVALID_SOCKET){
MessageBox(NULL, "创建套接字失败!", "Warning", MB_ICONEXCLAMATION);
closesocket(serverSocket);
WSACleanup();
}
sockaddr_in localaddr;
localaddr.sin_addr.s_addr = htonl(INADDR_ANY);
localaddr.sin_family = AF_INET;
localaddr.sin_port = htons(6000);
if(bind(serverSocket, (const struct sockaddr*)&localaddr, sizeof(localaddr)) == SOCKET_ERROR){
MessageBox(0,"绑定地址失败!","Warning", MB_ICONEXCLAMATION);
closesocket( serverSocket);
WSACleanup();
}
listen(serverSocket, 5);
while (true)
{
clientlen = sizeof(clientaddr);
SOCKET connfd = accept(serverSocket, (struct sockaddr*) &clientaddr, &clientlen);
hp = gethostbyaddr((const char*) &clientaddr.sin_addr.S_un, sizeof(clientaddr.sin_addr.S_un), AF_INET);
haddrp = inet_ntoa(clientaddr.sin_addr);
cout << "server connected to " << hp->h_name <<"( "<<haddrp<<" )"<<endl;
int length;
//char buffer[5];
//if ((length = recv(connfd, buffer, 5, 0)) == SOCKET_ERROR)
char buffer[10240];
if ((length = recv(connfd, buffer, 10240, 0)) == SOCKET_ERROR)
MessageBox(0,"接收失败!","Warning", MB_ICONEXCLAMATION);
for(int i=0;i<length;i++)
cout<<buffer[i];
cout<<endl;
closesocket(connfd);
}
closesocket( serverSocket);
WSACleanup();
return 0;
} 客户端代码:
C/C++ code
#include <winsock2.h>
#include <iostream>
#include <windows.h>
#include <memory.h>
using namespace std;
int main(){
struct hostent *hp;
struct in_addr addr;
struct sockaddr_in serverAddr;
WSADATA wsaData;
int ret = WSAStartup(MAKEWORD(2,2), &wsaData);
if(ret != 0){
cout << "Error" << endl;
WSACleanup();
}
SOCKET clientfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientfd == INVALID_SOCKET)
{
MessageBox(0,"创建套接字失败!","Warning", MB_ICONEXCLAMATION);
closesocket(clientfd);
WSACleanup();
}
addr.s_addr = inet_addr("192.168.168.135");
hp = gethostbyaddr((const char *)&addr,sizeof(addr),AF_INET);
memset(&serverAddr,'\0',sizeof(struct sockaddr_in));
memcpy((char*)&serverAddr.sin_addr,(char *)hp->h_addr_list[0],hp->h_length); //OK
serverAddr.sin_family = hp->h_addrtype;
serverAddr.sin_port = htons(6000);
if(connect(clientfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr))<0)
cout<<"error"<<endl;
int length;
char buffer[5];
for(int i=0;i<5;i++)
buffer[i]='a';
if ((length = send(clientfd, buffer, 5, 0)) == SOCKET_ERROR)
MessageBox(0,"发送失败!","Warning", MB_ICONEXCLAMATION);
return 0;
}