C语言 socket 传输
发布网友
发布时间:2022-05-18 18:36
我来回答
共1个回答
热心网友
时间:2023-10-23 15:07
///////////////////////////////////////////
//server
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WSADATA wsaData;
int ret = WSAStartup(MAKEWORD(2,2), &wsaData);
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//本地地址信息
sockaddr_in localAddr;
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(5000);//本地端口
localAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if(!bind(s,(sockaddr *)&localAddr,sizeof(sockaddr)))
printf("bind ok\n");
//远程主机地址
sockaddr_in remoteAddr;
intremoteAddrLen = sizeof(sockaddr);
listen(s,5);
SOCKET remoteSocket;
while(1)
{
remoteSocket = accept(s,(sockaddr *)&remoteAddr,&remoteAddrLen);
if(remoteSocket!= -1)
break;
}
printf("connection from remote\n");
char buf[100] = { 0 };
int bufLen = 100;
recv(remoteSocket, buf, bufLen, 0);
printf("%s", buf);
system("pause");
return 0;
}
//////////
//client
/////////
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
int main()
{
WSADATA wsaData;
int ret = WSAStartup(MAKEWORD(2,2), &wsaData);
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
//本地地址信息
sockaddr_in localAddr;
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(9999);//本地端口
localAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
bind(s,(sockaddr *)&localAddr,sizeof(sockaddr));
//远程主机地址
sockaddr_in remoteAddr;
remoteAddr.sin_family = AF_INET;
remoteAddr.sin_port = htons(5000);//远程端口
remoteAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");// 远程IP地址
ret = connect(s,(sockaddr *)&remoteAddr,sizeof(sockaddr));
if(!ret) {
printf("connection ok\n");
}
ret = send(s, "hello", 6, 0);
printf("%d bytes sended\n", ret);
closesocket(s);
WSACleanup();
system("pause");
return 0;
}