关于TCO聊天的一些求助
我在自己的笔记本上练习一些关于TCP聊天软件的视频,但是出现了一些程序崩溃的问题,我的ip是:
无线局域网适配器 WLAN:
连接特定的 DNS 后缀 . . . . . . . :
IPv6 地址 . . . . . . . . . . . . : 2409:8a1e:c91c:39c0:f098:aea1:90ea:f133
临时 IPv6 地址. . . . . . . . . . : 2409:8a1e:c91c:39c0:d55a:db3e:39bd:1777
本地链接 IPv6 地址. . . . . . . . : fe80::f098:aea1:90ea:f133%14
IPv4 地址 . . . . . . . . . . . . : 192.168.1.5
子网掩码 . . . . . . . . . . . . : 255.255.255.0
默认网关. . . . . . . . . . . . . : fe80::1%14
192.168.1.1
程序代码如下:
程序代码:
//服务器端 #include<stdio.h> //#include<windows.h> #include<winsock.h> #pragma comment(lib,"ws2_32.lib") int main() { WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); if (LOBYTE(wsadata.wVersion)!=2|| HIBYTE(wsadata.wVersion) != 2) { printf("请求协议版本失败\n"); return -1; } printf("请求协议成功\n"); SOCKET serverSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (SOCKET_ERROR == serverSocket) { printf("创建套接字失败\n"); WSACleanup(); return -2; } printf("创建套接字成功\n"); SOCKADDR_IN addr = { 0 }; addr.sin_family = AF_INET; addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.1"); addr.sin_port = htons(10086); int r = bind(serverSocket, (SOCKADDR*)&addr, sizeof addr); if (-1==r) { printf("bind失败\n"); closesocket; WSACleanup(serverSocket); return 0; } printf("bind成功"); r = listen(serverSocket, 10); if (-1 == r) { printf("监听失败\n"); closesocket; WSACleanup(serverSocket); return -4; } printf("监听成功\n"); SOCKADDR_IN cAddr = { 0 }; double len =sizeof cAddr; SOCKET clientSocket = accept(serverSocket,(SOCKADDR*)&cAddr,&len ); if (SOCKET_ERROR == clientSocket) { printf("服务器宕机了\n"); closesocket; WSACleanup(serverSocket); return -5; } printf("有客户端连接到服务器了:%s\n",inet_ntoa(cAddr.sin_addr)); char buff[1024]; while (1) { r = recv(clientSocket, buff, 1023, NULL); if (r>0) { buff[r] = 0; printf(">>%s\n", buff); } } while (1) return 0; }
程序代码:
//客户端 #include<stdio.h> //#include<windows.h> #include<winsock.h> #pragma comment(lib,"ws2_32.lib") int main() { WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); if (LOBYTE(wsadata.wVersion) != 2 || HIBYTE(wsadata.wVersion) != 2) { printf("请求协议版本失败\n"); return -1; } printf("请求协议成功\n"); SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (SOCKET_ERROR == clientSocket) { printf("创建套接字失败\n"); WSACleanup(); return -2; } printf("创建套接字成功\n"); SOCKADDR_IN addr = { 0 }; addr.sin_family = AF_INET; addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.1"); addr.sin_port = htons(10087); int r = connect(clientSocket, (SOCKADDR*)&addr, sizeof addr); if (r == -1) { printf("链接服务器失败\n"); return 0; } printf("连接服务器成功\n"); char buff[1024]; while (1) { memset(buff, 0, 1024); printf("你想说啥\n"); scanf_s("%s",&buff); send(clientSocket, buff, strlen(buff), NULL); } return 0; }
但在运行后会服务端会在bind环节失败并崩溃:
请求协议成功
创建套接字成功
bind失败
同时弹窗出现debug Error,
program..........\TCP S.exe
Modlue......\TCP S.exe
File:
runtime check failture#0.......
客户端会在连接环节崩溃:
请求协议成功
创建套接字成功
有时也会出现和服务端一样的弹窗,请问要怎么改。