windows socket编程 server client
socket
windows
//server.cpp
#include <stdio.h>
#include <WinSock2.h>
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma comment(lib,"ws2_32.lib")
#define BUF_SIZE 100
int main()
{
//初始化dll
WSADATA wsaData;
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("127.0.0.1");//具体的IP地址 这里是本机地址
sockAddr.sin_port = htons(1234);//端口
bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));
//进入监听
listen(servSock, 20);
//接收客户端请求
SOCKADDR clntAddr;
int nSize = sizeof(SOCKADDR);
char buffer[BUF_SIZE];//缓冲区
while(1)
{
SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize);
int strLen = recv(clntSock, buffer, BUF_SIZE, 0);//接受客户端信息
printf("message received from client:%s\n", buffer);
send(clntSock, buffer, strLen, 0);//原样发回
closesocket(clntSock);//关闭本次连接
memset(buffer, BUF_SIZE, 0);//重置缓存区
}
//关闭套接字
closesocket(servSock);
//中止DLL使用
WSACleanup();
return 0;
}
//client.cpp
#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
//加载ws2_32.dll
#define BUF_SIZE 100
int main()
{
//初始化DLL
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//向服务器发起请求
sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr));//每个字节都用0填充
sockAddr.sin_family = PF_INET;//使用ipv4地址
sockAddr.sin_addr.s_addr = inet_addr("127.0.0.1");//具体的IP地址 这里是本机地址
sockAddr.sin_port = htons(1234);//端口
char bufSend[BUF_SIZE] = { 0 };//发送缓冲区
char bufRecv[BUF_SIZE] = { 0 };//接受缓冲区
while (1)
{
//创建套接字
SOCKET sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
connect(sock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));
printf("input your message:");
gets_s(bufSend);
send(sock, bufSend, BUF_SIZE, 0);
//接受服务器传回的数据
recv(sock, bufRecv, BUF_SIZE, 0);
//输出接收到的数据
printf("Message from server:%s\n", bufRecv);
memset(bufSend, 0, BUF_SIZE);
memset(bufRecv, 0, BUF_SIZE);
closesocket(sock);
}
WSACleanup();
system("pause");
return 0;
}
在socket使用域名
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
//加载动态库DLL
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//域名解析
struct hostent* host = gethostbyname("www.baidu.com");
if(!host)
{
puts("Get IP address error!");
system("pause");
exit(0);
}
//别名
for (int i = 0; host->h_aliases[i]; i++)
{
printf("Aliases %d:%s\n", i + 1, host->h_aliases[i]);
}
//地址类型
printf("Address type:%s\n", (host->h_addrtype==AF_INET)?"AF_INET":"AF_INET6");
for (int i = 0; host->h_addr_list[i]; i++)
{
printf("IP addr %d: %s\n", i + 1, inet_ntoa(*(struct in_addr*)host->h_addr_list[i]));
}
system("pause");
return 0;
}
hello