只有8080端口接受信息的服务器程序编写
#include <stdio.h>
#include <iostream>
#include <winsock2.h>
#pragma comment (lib, "ws2_32.lib")//加载 ws2_32.dll
using namespace std;
int main() {
int retVal;//调用各种Socket函数的返回值
char buf1[1024];//用于接收客户端数据的缓冲区
WSADATA wsaData;
memset(buf1, '\0', sizeof(buf1));//清空数据接收缓冲区
WSAStartup(MAKEWORD(2, 2), &wsaData);//初始化
SOCKET servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);//创建套接字
sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充
sockAddr.sin_family = PF_INET;//使用IPv4地址
sockAddr.sin_addr.s_addr = inet_addr("主机地址");//具体的IP地址
sockAddr.sin_port = htons(8080);//端口
retVal = bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));//绑定套接字
if (retVal < 0)
{
cout << "绑定失败!" << endl;
}
retVal = listen(servSock, 5); //进入监听状态
if (retVal < 0)
{
cout << "监听失败!" << endl;
}
SOCKADDR clntAddr;
int nSize = sizeof(SOCKADDR);
SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize);//接收客户端请求
if (retVal < 0)
{
cout << "连接失败!" << endl;
}
else
cout << "连接成功!" << endl;
retVal = recv(clntSock, buf1, 1024, 0);
if (retVal < 0)
{
cout << "接收错误!" << endl;
}
//cout << buf1 << endl;
char* id = strstr(buf1, "user=");
char* sign = strstr(buf1, "&");
char* passwd = strstr(buf1, "pwd=");
cout << "提取成功!" << endl;
cout << "账号:";
for (int i = 0; i < sign - id - 5; i++)
{
cout << *(id + 5 + i);
}
cout << " 密码:";
cout << passwd + 4 << endl;
closesocket(clntSock);//关闭套接字
closesocket(servSock);//关闭套接字
WSACleanup();
return 0;
}