在本机测试可以连接,二台电脑测试就不行了,这是为什么??
服务器代码:
#include <iostream>
#include <stdlib.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
SOCKET sock_id, client_id;
struct sockaddr_in serv_addr, remote_addr;
wVersionRequested = MAKEWORD(2, 0);
if (0 != WSAStartup(wVersionRequested, &wsaData))
{
cout << "加载Winsock库出错!" << endl;
exit(1);
}
if (-1 == (sock_id = socket(AF_INET, SOCK_STREAM, 0)))
{
cout << "创建套接字出错!" << endl;
exit(1);
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(800);
serv_addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.10");
memset(&(serv_addr.sin_zero), 0, sizeof(serv_addr.sin_zero));
if (SOCKET_ERROR == bind(sock_id, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)))
{
cout << "1出错!" << endl;
exit(1);
}
if (SOCKET_ERROR == listen(sock_id, 5))
{
cout << "2出错!" << endl;
exit(1);
}
int sin_size = sizeof(struct sockaddr_in);
if (SOCKET_ERROR == (client_id = accept(sock_id, (struct sockaddr *)&remote_addr, &sin_size)))
{
cout << "3出错!" << endl;
exit(1);
}
send(client_id, "Hello World!", strlen("Hello World!"), 0);
closesocket(client_id);
closesocket(sock_id);
WSACleanup();
return 0;
}
客户端代码:
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
const int SIZE = 100;
char temp[SIZE];
int recvbytes;
WORD wVersionRequested;
WSADATA wsaData;
SOCKET sock_id, client_id;
struct sockaddr_in serv_addr;
wVersionRequested = MAKEWORD(2, 0);
if (0 != WSAStartup(wVersionRequested, &wsaData))
{
cout << "加载Winsock库出错!" << endl;
exit(1);
}
if (-1 == (sock_id = socket(AF_INET, SOCK_STREAM, 0)))
{
cout << "出错!" << endl;
exit(1);
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(800);
serv_addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.10");
memset(&(serv_addr.sin_zero), 0, sizeof(serv_addr.sin_zero));
if (SOCKET_ERROR == (client_id = connect(sock_id, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr))))
{
cout << "出错!" << endl;
exit(1);
}
if (ERROR_SUCCESS == (recvbytes = recv(sock_id, temp, SIZE, 0)))
{
cout << "接受数据出错!" << endl;
exit(1);
}
temp[recvbytes] = '\0';
cout << temp << endl;
closesocket(client_id);
closesocket(sock_id);
WSACleanup();
return 0;
}