tcpip实验报告 下载本文

内容发布更新时间 : 2024/12/27 11:29:37星期一 下面是文章的全部内容请认真阅读。

实验流程图: 开始

输入用户名

密码等相关

信息

连接服务器

是否连接 成功? 发送错误信息

结束

实验代码:

#include #include #include #include #include

#pragma comment(lib,\#define DEFAULT_PORT 21 #define DATA_BUFFER 1024 char *SERIP=\//初始化函数 int load()

显示连接成功 获取 {

time_t timep;

char *wday[] = {\

struct tm *p; time(&timep);

p = localtime(&timep); //取得当地时间

cout<<(1900+p->tm_year)<<\ \

cout<tm_wday]<<\ \ }

SOCKET bindIpAddr(char *IP,unsigned short port) { }

void main() {

WSADATA wsaData; SOCKET sock;

sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

sockaddr_in SerAddr; SerAddr.sin_family=AF_INET; SerAddr.sin_port=htons(port);

SerAddr.sin_addr.S_un.S_addr=inet_addr(SERIP); int error;

error=bind(sock,(sockaddr *)&SerAddr,sizeof(sockaddr)); if(error==SOCKET_ERROR) { } {

closesocket(sock); }

return sock;

return INVALID_SOCKET; closesocket(sock); return SOCKET_ERROR; WORD wVersionRequested; WSADATA wsaData; int error;

wVersionRequested=MAKEWORD(2,2);

error=WSAStartup(wVersionRequested, &wsaData); if(error!=0) else

return 0;

return -1;

if(listen(sock,5)==INVALID_SOCKET)

SOCKET sClient,sData,sListen; char name[10]; char pass[10]; int iLen;

//从服务器端接收的数据长度

//接收数据缓冲区

char buf[DATA_BUFFER]; char databuf[DATA_BUFFER]; struct sockaddr_in ser; struct sockaddr_in dat; if(load()!=0) { };

//连接服务器的地址信息 ser.sin_family=AF_INET;

cout<<\初始化错误!\return;

//服务器端地址 //服务器端地址

//接收缓冲区初始换

memset(buf,0,sizeof(buf));

ser.sin_port=htons(DEFAULT_PORT); ser.sin_addr.S_un.S_addr=inet_addr(SERIP); //建立客户端套接口

sClient=socket(AF_INET,SOCK_STREAM,0); if(sClient==INVALID_SOCKET) { }

//请求与服务器端建立TCP连接

if(connect(sClient,(struct sockaddr*)&ser,sizeof(ser))==INVALID_SOCKET) { }

char cinbuf[100]; //从服务器端接收数据

iLen=recv(sClient,buf,sizeof(buf),0); cout<

memset(buf,0,sizeof(buf)); iLen=0;

cout<<\strcpy(cinbuf,\cin>>name; strcat(cinbuf,name); strcat(cinbuf,\

//接收缓冲区初始换

//接收缓冲区初始换

memset(databuf,0,sizeof(databuf));

cout<<\return;

cout<<\return;

if(send(sClient,cinbuf,strlen(cinbuf),0)==SOCKET_ERROR) { }

iLen=recv(sClient,buf,sizeof(buf),0); cout<>pass; strcat(cinbuf,pass); strcat(cinbuf,\

if(send(sClient,cinbuf,strlen(cinbuf),0)==SOCKET_ERROR) { }

iLen=recv(sClient,buf,sizeof(buf),0); cout<

cout<<\:\cout<<\cin>>input;

if(!strcmp(input,\{

strcpy(cinbuf,\strcat(cinbuf,\strcat(cinbuf,\

if(send(sClient,cinbuf,strlen(cinbuf),0)==SOCKET_ERROR) { }

iLen=recv(sClient,buf,sizeof(buf),0); cout<

sListen=bindIpAddr(SERIP,5400); if(sListen==INVALID_SOCKET) { }

int jj=sizeof(ser); strcpy(cinbuf,\strcat(cinbuf,\

cout<<\绑定失败!\cout<<\发送失败!\return;

cout<<\发送失败!\return;

cout<<\发送失败!\return;

}

} else

if(send(sClient,cinbuf,strlen(cinbuf),0)==SOCKET_ERROR) { }

sData=accept(sListen,(struct sockaddr*)&dat,&ii); if(sData==INVALID_SOCKET) { }

iLen=recv(sClient,buf,sizeof(buf),0); cout<

recv(sData,databuf,sizeof(databuf),0); cout<

cout<<\return;

cout<<\发送失败!\return;

return;

closesocket(sClient); WSACleanup();

实验结果: